← Back to journal JavaScript Events: What Happens When You Click a Button?

JavaScript Events: What Happens When You Click a Button?

A beginner-friendly look at how a web page hears clicks, runs JavaScript, and updates what you see.

A page that can listen

HTML describes what is on a page. CSS describes how it looks. JavaScript lets the page respond when something happens: a click, a key press, or a message from a server.

Imagine a doorbell. The button is on the page, JavaScript is listening for the press, and the code you write is what happens after the bell rings. In a browser, this is called an event.

Person clicks→Browser fires event→Your code runs

Connect a click to a function

Here is a small example. The HTML gives a button and a place for a message. JavaScript waits for a click and then changes the message.

<button id="hello-button">Say hello</button>
<p id="message"></p>

<script>
  const button = document.querySelector("#hello-button");
  const message = document.querySelector("#message");

  button.addEventListener("click", () => {
    message.textContent = "Hello!";
  });
</script>

querySelector finds an element in the page. addEventListener tells the browser, “When this kind of event happens, run this function.” The arrow function is the instructions to run. You do not need to understand every symbol at once; focus on the order: find, listen, respond.

Why not do everything right away?

Some work takes time. Asking a server for a profile, a photo, or a search result might take a fraction of a second—or longer if the connection is slow. If the browser froze while waiting, the page would feel broken.

JavaScript can start that request and keep the page responsive. The await keyword means “pause this function here until the result arrives.” It does not freeze the whole page.

async function loadProfile() {
  const response = await fetch("/api/profile");
  const profile = await response.json();
  console.log(profile.name);
}

fetch sends a web request. The response arrives later, so the function is marked async and uses await. Real code should also handle failures with try and catch, so a lost connection can show a useful message instead of an error screen.

What to remember

JavaScript does not magically know what you want a button to do. You connect an event to a function, and the function changes the page or asks another system for data. Once that pattern makes sense, menus, forms, search boxes, and chat screens become variations of the same idea.

A good first exercise: add a button that counts how many times it has been clicked. Keep the count in a variable, add one on each click, and write the new number into the page.