Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Events – JavaScript

Summary

To create an event handler in JavaScript, use the addEventListener() method:

element.addEventListener('click', () => {
  
});

Alternatively, you can use an event handler property:

element.onclick = function() {

}

Details

An event handler allows you to add code in your JS file that will run when certain user actions occur, like the user clicking on a button or hovering over an element on the page. You can use either method above to create event handlers in JavaScript.

addEventListener() method

The addEventListener() method allows you to add the same type of listener to an element multiple times. For example, you could add multiple listeners for mouse clicks, as in the example below:

element.addEventListener('click', () => {
  // Add code here
});

element.addEventListener('click', () => {
  // Add different code here
});

Another advantage of the addEventListener() method is that you can use the removeEventListener() method to remove event handler code from an element. This is not possible with event handler properties. You likely won’t need removeEventListener() for simple websites, but it can be useful for more complex ones.

Event handler properties

Event handler properties are the older way of writing and have better cross-browser support.

List of all events

To see a list of all possible events, visit the following link:

Event reference on MDN

Demo

Exercises

First recreate the HTML code from the Demo section. Then recreate the JS code from the Demo section in your JS file. Then try customizing the text for the div element.

References

Introduction to events on MDN

Back to: JavaScript Reference > JS DOM