...

/

Testing Events

Testing Events

Learn how to test JavaScript DOM events.

JavaScript DOM events

We can react to user actions by attaching event listeners to nodes in the DOM. Using the addEventListener method, we can attach one or more listeners.

When the user takes an action, such as clicking on a page element, JavaScript generates events that carry information about the user action.

Our event listeners watch for a matching event and then run a callback function to carry out a desired action.

Press + to interact
let myButton = document.querySelector('button');
myButton.addEventListener('click', () => {
console.log('My button was clicked');
});

If we want to remove that event listener later on, we can use a named function as given below:

Press + to interact
let myButton = document.querySelector('button');
function clickHandler() {
console.log('My button was clicked');
}
myButton.addEventListener('click', clickHandler());
// Later, we can remove the handler
myButton.removeEventListener('click', clickHandler());

There are many different DOM events we can listen for, including the following:

  • blur
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mouseenter
  • mouseleave
  • mousemove
  • mouseover

Our event listener function addEventListener receives an event, such as click, which carries information about the event. For example, we can use it to determine the target node where the event originated:

Press + to interact
let myButton = document.querySelector('button');
myButton.addEventListener('click', event => {
console.log(event.target.nodeName); // BUTTON
});

We can also determine the key pressed using the event object as given below:

Press + to interact
window.addEventListener('keydown', event => {
if (event.key === 'x') {
console.log('X key was pressed');
}
});

Event bubbling

...