<button>Change color</button>

const btn = document.querySelector("button");

function random(number) { return Math.floor(Math.random() * (number + 1)); }

btn.addEventListener("click", () => { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; });

  • The HTML <button> element will fire a click event when the user clicks it. We call the addEventListener() method on it to add an event listener; this takes two parameters:

the string "click", to indicate that we want to listen to the click event. Buttons can fire lots of other events, such as "mouseover" when the user moves their mouse over the button, or "keydown" when the user presses a key and the button is focused. a function to call when the event happens. In our case, the defined anonymous function generates a random RGB color and sets the background-color of the page <body> to that color.

  • You could also create a separate named function, and reference that in the second parameter of addEventListener(), like this:

const btn = document.querySelector("button");

function random(number) { return Math.floor(Math.random() * (number + 1)); }

function changeBackground() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }

btn.addEventListener("click", changeBackground);

  • Listening for other events

There are many different events that can be fired by a button element. Let's experiment.

First, make a local copy of random-color-addeventlistener.html, and open it in your browser. It's just a copy of the simple random color example we've played with already. Now try changing click to the following different values in turn, and observing the results in the example:

focus and blur — The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value. dblclick — The color changes only when the button is double-clicked. mouseover and mouseout — The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.

Some events, such as click, are available on nearly any element. Others are more specific and only useful in certain situations: for example, the play event is only available on elements that have play functionality, such as <video>.

  • Removing listeners

If you've added an event listener using addEventListener(), you can remove it again if desired. The most common way to do this is by using the removeEventListener() method. For example, the following line would remove the click event handler we saw previously:

btn.removeEventListener("click", changeBackground);

  • For simple, small programs, cleaning up old, unused event handlers isn't necessary, but for larger, more complex programs, it can improve efficiency. Also, the ability to remove event handlers allows you to have the same button performing different actions in different circumstances: all you have to do is add or remove handlers.
  • Adding multiple listeners for a single event

By making more than one call to addEventListener(), providing different handlers, you can have multiple handler functions running in response to a single event:

  • myElement.addEventListener("click", functionA);

myElement.addEventListener("click", functionB);

  • Other event listener mechanisms

We recommend that you use addEventListener() to register event handlers. It's the most powerful method and scales best with more complex programs. However, there are two other ways of registering event handlers that you might see: event handler properties and inline event handlers. Event handler properties

Objects (such as buttons) that can fire events also usually have properties whose name is on followed by the name of an event. For example, elements have a property onclick. This is called an event handler property. To listen for the event, you can assign the handler function to the property.

For example, we could rewrite the random color example like this:

  • const btn = document.querySelector("button");

function random(number) { return Math.floor(Math.random() * (number + 1)); }

btn.onclick = () => { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; };

  • You can also set the handler property to a named function:
  • const btn = document.querySelector("button");

function random(number) { return Math.floor(Math.random() * (number + 1)); }

function bgChange() { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }

btn.onclick = bgChange;

  • Event handler properties have disadvantages compared to addEventListener(). One of the most significant is that you can't add more than one listener for a single event. The following pattern doesn't work, because any subsequent attempts to set the property value will overwrite earlier ones:
  • element.onclick = function1;

element.onclick = function2;

  • Inline event handlers — don't use these

You might also see a pattern like this in your code:

  • <button onclick="bgChange()">Press me</button> DO NOT USE.
  • function bgChange() {

const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; document.body.style.backgroundColor = rndCol; }

  • The earliest method of registering event handlers found on the Web involved event handler HTML attributes (or inline event handlers) like the one shown above — the attribute value contains the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a <script> element on the same page, but you could also insert JavaScript directly inside the attribute, for example:
  • You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient.

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents.

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

  • const buttons = document.querySelectorAll("button");

for (const button of buttons) { button.addEventListener("click", bgChange); }

  • Finally, many common server configurations will disallow inline JavaScript, as a security measure.

You should never use the HTML event handler attributes — those are outdated, and using them is bad practice.

  • Event objects

Sometimes, inside an event handler function, you'll see a parameter specified with a name such as event, evt, or e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example to include an event object:

  • const btn = document.querySelector("button");

function random(number) { return Math.floor(Math.random() * (number + 1)); }

function bgChange(e) { const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`; e.target.style.backgroundColor = rndCol; console.log(e); }

btn.addEventListener("click", bgChange);

  • Here you can see we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element the event occurred upon. So, in this example, we are setting a random background color on the button, not the page.
  • Extra properties of event objects

Most event objects have a standard set of properties and methods available on the event object; see the Event object reference for a full list.

Some event objects add extra properties that are relevant to that particular type of event. For example, the keydown event fires when the user presses a key. Its event object is a KeyboardEvent, which is a specialized Event object with a key property that tells you which key was pressed:

  • <input id="textBox" type="text" />

<div id="output"></div>

  • const textBox = document.querySelector("#textBox");

const output = document.querySelector("#output"); textBox.addEventListener("keydown", (event) => { output.textContent = `You pressed "${event.key}".`; });

jun 9 2026 ∞
jun 9 2026 +