JavaScript is responsible for the behaviour of your website/app. At the heart of affecting the behaviour of the page is listening for user interaction events. These are things like button clicks, key presses and drags and drops.

To do this, first we select an element then we add an event listener. To add an event listener we use the “addEventListener” function like this:

var button = document.querySelector( "button" );

button.addEventListener( "click", function() {
  console.log( "SOMEONE PLAY SOME ROXETTE!" );
} );

A common pattern is to add event listeners to a set of elements, like each item in a list so each item is clickable. The code for this would look like this:

var listItems = document.querySelectorAll( "li" );
for ( var i = 0; i < listItems.length; i++ ) {
    listItems[ i ].addEventListener( "click", function () {
        this.style.color = "pink";
    } );
}

You can also add multiple event listeners to the same element. So, for example, you can listen for a hover and a click on the same button and take separate actions for each. Listen events are very powerful and a great addition to your JavaScript coding toolbelt.


Posted

in

by