# Event listeners

Events are triggered all the time inside a webpage!

The browser itself already generates a number of events, for example after loading the page, when resizing the window, ... The user can also trigger events, for example by clicking on a link, pressing a key, scrolling with the mouse, submitting a form, ...

A complete list of all possible events (opens new window) can be found on the Mozilla website

With event listeners we can interact (run a function) every time the event takes place On this page we discuss a few commonly used events. If you understand how this works you can make your own event listeners to interact with every possible event.

An event listener has always two (sometimes three) parameters:

  1. the <event> to watch for,
  2. the callback function that will be executed when the event fires
  3. (optional) a boolean value to handle event bubbling, default value is false which enables bubbling, true enables capturing (more info about the difference can be found here: Bubbling vs Capturing (opens new window))

 





 


<element>.addEventListener('<event>', function(e) {
  // do something when the <event> is triggered
  // 'e' is the event itself
});

// or with an arrow function
<element>.addEventListener('<event>', e => {
  // ...
});
1
2
3
4
5
6
7
8
9

# Mouse events

In this example, we use four mouse events

event description
click the mouse button is pressed and released on an element
dblclick the mouse button is clicked twice on an element
mouseenter the cursor comes over an element
mouseleave the cursor leaves an element

In this example, we only change some classes on #section1:

  • btnShow, btnHide and btnToggle switch the opacity property of #section1 between 0 and 1 and the max-height property between 0 and 300px
  • When hovering #section2 (mouseenter event) , #section1 rotates 180 degrees around its X-axis
  • When leaving #section2 (mouseleave event) , #section1 rotates back to 0 degrees

See the Pen FSELStatic by Jitse Beyens (@BeyensJ) on CodePen.

# Window events

In this example we constantly (re)calculate the real height of the section1 and display it at the bottom of this section, this can be done with the resize event listener on the window object

In this example we use the window.getComputedStyle() (opens new window) method to return a live object containing the values of all CSS properties of the element. We are only interested in the height value of the section and we will display that in the bottom in the span. Every time we resize the window, we get the new height of the section and update the span.

See the Pen FSELWindow by Jitse Beyens (@BeyensJ) on CodePen.

# Event bubbling

When an event happens on an element, it first runs the callback function of the corresponding event listener after which the event bubbles up the DOM tree.

Look at the DOM structure, we set a click event on the figure, the img, the figcaption and the b tag inside the figcaption

Event bubbling

When you click on the b element, the event bubbles up the DOM tree, and (it looks as) you also have clicked on the figcaption and on the figure! Sometimes this may lead to unexpected behavior ...

You can stop this "bubbling" behavior by adding the stopPropagation() (opens new window) method to the event

See the Pen FSBubbling by Jitse Beyens (@BeyensJ) on CodePen.

# Prevent default action

Sometimes you want to prevent the default action from being executed, for example to do some client-side validation before actually submitting a form.

You can do so by adding the preventDefault() (opens new window) method to the event

In this example:

  • The default action (going to google.com) when clicking on the link is prevented.
  • window.open('https://bing.com', '_blank'): a new browser tab (bing.com) is opened
  • if the search term (#q) contains less than 3 characters, the default action of the event (submitting the form) is prevented

See the Pen FSPreventDefault by Jitse Beyens (@BeyensJ) on CodePen.

# Dispatch (trigger) event

The dispatchEvent() (opens new window) method automatically triggers an event

When the page loads, the click event on the button is automatically triggered

See the Pen FSTrigger by Jitse Beyens (@BeyensJ) on CodePen.

# Event on a NodeList

To add an event listener (listening to the same event and with the same callback function) to every element inside a NodeList, you first have to loop over the NodeList and add the event listener inside the loop

See the Pen FSEventNodeList by Jitse Beyens (@BeyensJ) on CodePen.

# Caution

# The this keyword

There is a huge difference between the meaning of the this keyword inside regular ES5 functions and inside ES6 arrow functions!

  • Regular function: this refers to the clicked button
  • Arrow function: this refers to the global window object, so you have to use e.target to refer to the clicked button

this keyword

REMARKS

In the example above, we used an anonymous/nameless arrow function as callback function for the event listener:

<element>.addEventListener('<event>', (e) => { ... });
1

Likewise, we can do so for the callbacks in the timing functions:

setTimeOut( () => { ... }, 1000);
setInterval( () => { ... }, 1000);
1
2

Because the meaning of the this keyword inside arrow functions, it's not advisable to use arrow functions as methods inside classes and objects

# Parsing numeric input fields

Numeric input fields ALWAYS return a numeric STRING and not a number

One of the most common errors with forms is adding two numeric strings (stemming from numeric input fields)

Last Updated: 4/24/2024, 1:13:07 PM