Add a click event listener to a button in JavaScript
Beginner · 4 min read
Almost everything interactive on a web page starts with a click. A "Buy now" button, a menu icon, a "Show more" link: each one waits for someone to click it and then runs some code. Connecting a click to your own function is the first real step toward pages that respond.
In this tutorial you will create a button with JavaScript, listen for clicks on it, record a message each time it is clicked, and then switch the listener off again. You need to know what a function is and a little HTML. Everything else is explained as we go.
What an event is
An event is the browser telling your code "something just happened". A click is an event. So is a key press, the mouse moving over an element, or a form being sent. Each kind of event has a name, written as a lowercase string such as 'click' or 'keydown'.
Your code doesn't keep checking whether the button was clicked. Instead, you hand the browser a function and say "run this when a click happens here". That function is called a listener, or an event handler.
addEventListener
Every element has a method called addEventListener. You give it two things: the name of the event and the function to run.
const button = document.createElement('button');
function onClick() {
console.log('clicked!');
}
button.addEventListener('click', onClick);
button.dispatchEvent(new Event('click')); // clicked!
The last line sends a click from code. dispatchEvent(new Event('click')) is handy for checking your work without reaching for the mouse, and we will use it in every step.
You may also see older code that writes button.onclick = onClick. That works, but the onclick property holds only one function. Assigning a second one quietly replaces the first. addEventListener lets an element have as many listeners as you need, so it is the one to learn.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
1 A button with a click listener
easyCreate a button, attach a click listener, and record a message when it is clicked.
Stuck? Three hints, smallest first
- 1.
addEventListener(‘click’, fn)is the modern way.onclick =allows only one handler. - 2. Registering the same function twice for the same event does nothing the second time.
- 3. A named function can be removed later; an inline arrow function cannot.
Step 1: create the button
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Click me';
document.body.appendChild(button);
console.log(button.tagName); // BUTTON
createElement makes a new element that isn't on the page yet. textContent sets the words on it, and appendChild adds it to the end of the page's body.
The type = 'button' line is worth a habit. A button inside a form is a "submit" button by default, so clicking it sends the form and reloads the page. Setting the type to 'button' makes it a plain button that only runs your code.
Step 2: write a named handler
When the browser runs your listener, it passes it one argument: an event object that describes what happened. Two of its properties are useful straight away. event.type is the event's name, and event.target is the element it happened on.
const log = [];
function onClick(event) {
log.push(`clicked: ${event.type} on ${event.target.tagName}`);
}
Pushing a message into an array, instead of printing it, lets us count the clicks later. The function also has a name, onClick. You will see why that matters in Step 5.
Step 3: listen, then click
const log = [];
const button = document.createElement('button');
button.type = 'button';
document.body.appendChild(button);
function onClick(event) {
log.push(`clicked: ${event.type} on ${event.target.tagName}`);
}
button.addEventListener('click', onClick);
button.dispatchEvent(new Event('click'));
console.log(log); // ['clicked: click on BUTTON']
Look at how onClick is passed: no brackets after it. You are handing the function over, to be run later, on every click.
The natural slip is to write addEventListener('click', onClick()). The brackets run onClick once, straight away, with no event at all. Here that throws an error, because event is undefined and has no type. In other handlers it fails silently: the function runs once and its return value, usually undefined, becomes the "listener".
Step 4: adding the same listener twice
What if the same line runs twice?
const log = [];
const button = document.createElement('button');
function onClick(event) {
log.push(`clicked: ${event.type} on ${event.target.tagName}`);
}
button.addEventListener('click', onClick);
button.addEventListener('click', onClick); // ignored
button.dispatchEvent(new Event('click'));
console.log(log.length); // 1
Registering the same function for the same event a second time is ignored, so one click still gives one entry. Two functions that merely look the same are a different story:
const button = document.createElement('button');
let extra = 0;
button.addEventListener('click', () => extra++);
button.addEventListener('click', () => extra++);
button.dispatchEvent(new Event('click'));
console.log(extra); // 2
Each arrow function is a new function, even with identical code, so both run.
Step 5: remove the listener
button.removeEventListener('click', onClick);
button.dispatchEvent(new Event('click'));
console.log(log.length); // 1: the new click was not recorded
removeEventListener takes the same two arguments as addEventListener, and it needs the very same function you added. That is the reason for naming the handler. An arrow function written inline has no name you can pass back, so it can never be removed.
The full solution
The panel below creates the button, attaches onClick twice, clicks it, removes the listener and clicks again. Its checks confirm one click gives one entry, removing stops it, two separate arrow functions both run, and a click on a different button never reaches this listener. Press Run to see the output, and try the live demo too.
allow-scripts only, so it cannot reach this page.const log = [];
const button = document.createElement('button');
button.type = 'button'; // without this, a button in a form submits
button.textContent = 'Click me';
document.body.appendChild(button);
// Named, so it can be removed later. An inline arrow cannot be.
function onClick(event) {
log.push(`clicked: ${event.type} on ${event.target.tagName}`);
}
button.addEventListener('click', onClick);
button.addEventListener('click', onClick); // ignored: same function, same type
fire(button, 'click');
console.log('after one click:', log);
fire(button, 'click');
console.log('after two clicks:', log.length, 'entries');
button.removeEventListener('click', onClick);
fire(button, 'click');
console.log('after removing the listener:', log.length, 'entries (unchanged)');
// A different function IS a second listener, even with identical code.
let extra = 0;
button.addEventListener('click', () => extra++);
button.addEventListener('click', () => extra++);
fire(button, 'click');
const extraAfterOneClick = extra; // snapshot: later assertions click again
console.log('two separate arrow functions both ran:', extra);
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the button was created', button.tagName, 'BUTTON');
test('with an explicit type, so it cannot submit a form', button.type, 'button');
test('one click gives one entry', log.length, 2);
test('the message names the event', log[0], 'clicked: click on BUTTON');
test('registering the same function twice does not double it', log.length / 2, 1);
test('the target is the button itself', log[0].includes('BUTTON'), true);
test('removing the listener stops it', (() => { const before = log.length; fire(button, 'click'); return log.length - before; })(), 0);
test('two distinct arrows are two listeners', extraAfterOneClick, 2);
test('a click on something else does not reach it', (() => { const other = document.createElement('button'); document.body.appendChild(other); const before = log.length; fire(other, 'click'); return log.length - before; })(), 0);
test('the button is in the document', button.parentNode === document.body, true);
addEventListener over onclick =, because the property form holds one handler and the second assignment silently replaces the first. Two details fall out of that. Registering the same function for the same event twice is ignored — the assertion shows one click producing one entry — but two arrow functions with identical bodies are two different functions, so both run. And removeEventListener needs the same reference you passed in, which is the practical reason to name a handler you intend to remove.
button.type = 'button' is worth the line. A <button> inside a form defaults to type="submit", so a button meant to run a script instead submits the form and reloads the page.
Common mistakes
- Calling the function instead of passing it.
addEventListener('click', onClick())runsonClickonce, right away. PassonClickwith no brackets. - Using
onclickfor more than one handler. Each assignment replaces the last one. UseaddEventListener, which keeps them all. - Trying to remove an inline arrow function.
removeEventListener('click', () => ...)removes nothing, because that arrow is a brand-new function. Give the handler a name.
Try it yourself
- Add a
preelement to the page and show the count in it:clicks: 1,clicks: 2, and so on. - Add a second button, "Remove the listener", whose own click handler calls
removeEventListener. Check that further clicks on the first button do nothing. - Pass
{ once: true }as a third argument toaddEventListener. Click the button three times. How many entries are inlog?