Event Handling in JavaScript

In the previous lesson, we introduced the concept of an event, which is an input signal from the user to the DOM node. We also discussed how the event propagates through the DOM tree, and explained how to use JavaScript to catch the event, so that a proper feedback can be provided to the user.

And now, it is time to go over some of the most common events you are going to deal with in frontend development.

Mouse events

Let's start with the mouse events. When you place the mouse on top of the button and then click, this simple action fires five different events:

  • When you move the pointer onto the button, the mouseover event is fired.
  • When the pointer moves on top of the button, the mousemove event is fired.
  • When you press down, the mousedown event is fired.
  • When you release, the mouseup event is fired.
  • And after that, a click event will be fired.

If two click events happen close together, a dblclick (double click) event will be fired after the second click.

A pointer event object contains detailed information about exactly where the click happened. This information can be retrieved through the clientX and clientY properties.

javascript
1let button = document.getElementById("button");
2
3button.addEventListener("click", (event) => {
4  console.log("X: " + event.clientX);
5  console.log("Y: " + event.clientY);
6});

coordinates

Notice that different coordinates are returned when you click different points on the button.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

šŸŽ‰ Create an Account šŸŽ‰