Code From ZeroCode From Zero
← Back to Course
Lesson 2 of 4
Module 3 · Lesson 2⏱ ~10 minJS

Responding to Clicks

Making buttons that actually do something — your first step into interactive web pages.



Events: Listening for User Actions

An event is something that happens in the browser — a click, a key press, a page finishing loading, a mouse moving over an element. JavaScript can listen for these events and run code in response. This is called event handling, and it's the foundation of every interactive web page.

Think of it like a doorbell. The button on the wall (the HTML element) is waiting. When someone presses it (the click event), the chime rings (your JavaScript code runs). Without the wiring between the button and the chime, nothing would happen. Event handling is that wiring.

Common events you'll use all the time:

  • click — user clicks an element
  • input — user types in a text field
  • submit — user submits a form
  • mouseover — mouse enters an element
  • keydown — user presses a keyboard key

The onclick Attribute

The simplest way to respond to a click is the onclick attribute, placed directly on an HTML element:

html
<button onclick="alert('Clicked!')">
  Click me
</button>

When the user clicks the button, the JavaScript inside onclick runs. Try it — open an HTML file, add this button, and click it. The alert pops up!

You can run multiple statements by separating them with semicolons:

html
<button onclick="console.log('clicked'); alert('Clicked!');">
  Log and Alert
</button>

onclick is great for getting started and quick experiments, but it has limits. You can't easily run the same code for multiple buttons, and mixing HTML and JavaScript in one line gets messy fast. For real projects, you'll want a cleaner approach — and that's where getElementById comes in.


Getting Elements with getElementById

To work with HTML elements from JavaScript, you first need to find them. The most direct way is by their id attribute:

js
document.getElementById("myButton")

This searches the entire page for an element with id="myButton" and returns it. Once you have the element, you can attach behavior to it:

html
<button id="myButton">Click me</button>

<script>
  document.getElementById("myButton").onclick = function() {
    alert("You clicked the button!");
  };
</script>

Let's break that down:

  • document.getElementById("myButton") — finds the button element
  • .onclick — attaches a click handler to it
  • function() { ... } — the code that runs when clicked

This is cleaner than inline onclick because your JavaScript lives in one place. You can also attach the same function to multiple elements:

js
function sayHello() {
  alert("Hello!");
}

document.getElementById("btn1").onclick = sayHello;
document.getElementById("btn2").onclick = sayHello;

Now both buttons run the same code. If you want to change the message, you change it in one place — the sayHello function. That's the power of separating behavior from structure.


Changing Content

Responding to clicks is fun, but the real magic is changing the page in response. The .innerHTML property lets you replace the content of any element:

html
<h1 id="title">Original Title</h1>
<button id="changeBtn">Change Title</button>

<script>
  document.getElementById("changeBtn").onclick = function() {
    document.getElementById("title").innerHTML = "New Title!";
  };
</script>

When the user clicks "Change Title", the heading instantly updates — no page reload, no flicker. This is what makes web applications feel responsive and modern.

You can change anything: text, HTML structure, even images:

js
// Change text
document.getElementById("heading").innerHTML = "Welcome back!";

// Add HTML (yes, you can include tags!)
document.getElementById("result").innerHTML =
  "<strong>Success!</strong> Your changes were saved.";

// Change an image source
document.getElementById("profilePic").src = "new-photo.jpg";

A complete example — a button that toggles between two messages:

js
let isOriginal = true;

document.getElementById("toggleBtn").onclick = function() {
  const heading = document.getElementById("heading");

  if (isOriginal) {
    heading.innerHTML = "Changed!";
    isOriginal = false;
  } else {
    heading.innerHTML = "Original Text";
    isOriginal = true;
  }
};

This uses a variable (let isOriginal) to track which state we're in. Each click flips between the two messages. This simple pattern — track state, respond to clicks, update the page — is at the heart of every interactive web application.


Changing Styles

JavaScript can also modify CSS styles directly through the .style property:

html
<div
  id="colorBox"
  style="width: 200px; height: 200px; background-color: gray;"
></div>
<button id="changeColorBtn">Change Color</button>

<script>
  document.getElementById("changeColorBtn").onclick = function() {
    document.getElementById("colorBox").style.backgroundColor = "blue";
  };
</script>

Notice that CSS property names change slightly in JavaScript:background-color (with a hyphen) becomes backgroundColor (camelCase). This rule applies to all hyphenated CSS properties:

  • font-size style.fontSize
  • border-radius style.borderRadius
  • text-align style.textAlign
  • margin-top style.marginTop

A fun example — a button that cycles through rainbow colors:

js
const colors = ["red", "orange", "yellow", "green", "blue", "purple"];
let colorIndex = 0;

document.getElementById("rainbowBtn").onclick = function() {
  const box = document.getElementById("colorBox");
  box.style.backgroundColor = colors[colorIndex];
  colorIndex = (colorIndex + 1) % colors.length;
};

Each click advances to the next color in the array. The % (modulo) operator wraps back to 0 after the last color — an elegant way to cycle through a list forever.


Try It Yourself

Create a page with a button that changes a paragraph's text when clicked. Here's a template to get you started:

  1. Create an HTML file with a heading, a paragraph, and a button
  2. Give the paragraph an id (like myText)
  3. Give the button an id (like changeBtn)
  4. In a <script> tag, use getElementById to find the button
  5. Set its .onclick to a function that changes the paragraph's .innerHTML
  6. Bonus: add a second button that changes the text back

Test it in your browser. That satisfying moment when you click and the page changes? That's the feeling of bringing a website to life.


Key Terms

Event
Something that happens in the browser — a click, a key press, a page load. JavaScript can listen for events and run code when they occur (event handling).
onclick
An HTML attribute or JavaScript property that runs code when an element is clicked. Simple inline: onclick="alert('hi')" or JS: element.onclick = myFunction.
getElementById
A method that finds an HTML element by its id attribute. Returns the element so you can modify it. Example: document.getElementById('myBtn').
innerHTML
A property that gets or sets the HTML content inside an element. Changing it updates what the user sees on the page instantly.

Check Your Understanding

What is an event in JavaScript, and what does it mean to 'handle' one?

Answer: An event is something that happens in the browser — like a click, a key press, or a page loading. To handle an event means to write code that runs when that event occurs. For example, setting a button's onclick property tells the browser "when this button is clicked, run this function."

Why is getElementById preferred over inline onclick?

Answer: getElementById keeps your JavaScript separate from your HTML. This means you can change behavior without touching your HTML structure, attach the same function to multiple elements, and keep all your logic organized in one place. It scales much better as your project grows.

How do you change both the content and style of an element with JavaScript?

Answer: Use .innerHTML to change the content (what's inside the element) and .style to change CSS properties. For example: element.innerHTML = "New text"; and element.style.color = "blue";. Remember that hyphenated CSS property names become camelCase in JavaScript.