A Click Handler that Updates the Page
Lesson 11 of 38 in the JavaScript learning path.
How do I run JavaScript when a button is clicked?
A click listener is a function the browser calls when a pointing device or a keyboard activates a button. addEventListener registers that function on the element. Inside the handler, event.currentTarget is the button you bound, and you update the page from there. The sample keeps a complete flag, paints a status sentence with textContent, and disables the button after the lesson is marked done. A second button sets the flag back and paints again.
The button should be type button when it is not submitting a form. A button with no type defaults to submit, so a control dropped inside a form would navigate away before your status update matters. The script checks that each node exists before it binds a listener, and the first paint runs on load so the status is visible before any click. The console prints that sentence, then prints it again after each action.
Syntax & Parameters
button.addEventListener("click", (event) => {
event.currentTarget;
});
Example
Interactive preview available'use strict';
const button = document.querySelector('#mark-complete');
const reset = document.querySelector('#reset-lesson');
const status = document.querySelector('#lesson-status');
let complete = false;
let clicks = 0;
function paint() {
if (status !== null) {
status.textContent = complete
? 'Lesson marked complete on this device.'
: 'Lesson is not complete yet.';
}
if (button instanceof HTMLButtonElement) {
button.textContent = complete ? 'Completed' : 'Mark complete';
button.disabled = complete;
}
const tally = document.querySelector('#click-tally');
if (tally !== null) {
tally.textContent = `Completion clicks: ${clicks}`;
}
}
function onComplete(event) {
clicks += 1;
complete = true;
paint();
const host = event.currentTarget;
const name = host instanceof HTMLElement ? host.id : 'button';
console.log(`click on #${name}`);
console.log(status === null ? '' : status.textContent);
}
if (button !== null) {
button.addEventListener('click', onComplete);
}
if (reset !== null) {
reset.addEventListener('click', () => {
complete = false;
paint();
console.log(status === null ? '' : status.textContent);
});
}
paint();
console.log(status === null ? 'missing status' : status.textContent);
Expected Output
On load, console and #lesson-status: Lesson is not complete yet. #click-tally: Completion clicks: 0 After clicking Mark complete: click on #mark-complete Lesson marked complete on this device. Completion clicks: 1 After clicking Reset: Lesson is not complete yet.
Line-by-Line Walkthrough
- The script selects the complete button, the reset button, and the status region, and it starts with complete set to false.
- paint writes the not-complete sentence or the complete sentence into the status node with textContent.
- When the complete control is a button, paint also changes its label and disables it after the lesson is marked done.
- A tally node, when present, shows how many times the completion handler has run.
- onComplete increments the tally, sets complete to true, paints, and logs the id from event.currentTarget.
- currentTarget is the button the listener was added to, even if a later icon inside the button was the click target.
- The listener is registered only after a null check, so a page without the button does not throw.
- The reset listener clears the flag and paints again, without incrementing the completion tally.
- paint runs once before any click, and the console prints the not-complete sentence from that first paint.
- Both controls are expected to be type button so they do not submit a surrounding form and navigate away.
Common Pitfalls & Security
A button without an explicit type is a submit button. Inside a form it fires submit and may navigate before the student reads the status you just set. Bind the listener to the button you mean, and read currentTarget when you need that button rather than whatever nested node was hit. Disabling the button in the handler also blocks a double click from marking the lesson twice, but the reset path must enable it again by painting with complete false.
- Forgetting type="button" on a control that sits in a form submits the form and reloads the page.
- Writing the status with innerHTML parses the sentence. A status built from a name equal to the untrusted string <img src="x" alt="untrusted"> is an XSS hole. Use textContent.
- onclick attributes in HTML mix structure and behavior and are harder to remove. addEventListener keeps the function in the script.
- event.target can be a child of the button. Use currentTarget when you need the element that owns the listener.
- A listener added inside another click stacks duplicates. Register the completion listener once, outside the handler.
Best Practices & Modern Standards
Use a real button for an on-page action, give it type button unless it submits a form, and listen with addEventListener. Keep the visible sentence in one paint function so the load path and the click path cannot disagree. ES2024 does not change the click event. The modern habit is a checked query, a listener, and textContent for the message.
Update ARIA or the disabled state in the same paint so assistive tech matches the words on screen. Log the status text you wrote, not a second string that might drift. When many rows need the same click behavior, move to one listener on the parent instead of binding a fresh handler per row.
Real-World Use
A lesson player has a Mark complete button under the video. The click sets a local flag, writes "Lesson marked complete on this device," and disables the button so a second click does not inflate the tally. Reset is there for the student who marked the wrong lesson while practicing.
The status region is text, not markup, so the sentence cannot pick up a tag from a lesson title that was concatenated by mistake. The same paint function runs on load, which means a refreshed page shows the not-complete sentence until the student clicks again. A later lesson can replace the local flag with a real save.
Frequently Asked Questions
Why does the page reload when I click?
The button is probably inside a form and its type defaults to submit. Set type="button" for an action that should stay on the page. Use type="submit" only when the click is supposed to submit the form.
What is the difference between target and currentTarget?
target is the deepest node that was hit. currentTarget is the node the listener is attached to. For a button that contains an icon, target may be the icon and currentTarget is still the button.
Can I update the page before the listener runs?
Yes. Call the same paint function on load so the status exists before the first click. The listener then changes state and calls paint again. One function keeps the sentences consistent.
Should the handler build HTML?
No. Put the status sentence in textContent. If any part of the sentence comes from a student or from a lesson title, innerHTML would parse it and open an XSS hole. A fixed sentence is still clearer as text.