Event Listeners

Page section: posts

Syntax

The addEventListener typically takes two parameters, the event type itself like click and a function. An optional third parameter is used to specify whether to use event bubbling or event capturing.

const button = document.getElementById('btn');

// where myFunction has been declared
button.addEventListener('click', myFunction);

NB. Notice that myFunction isn’t followed with the usual brackets: myFunction(). This is a callback function. Adding parentheses will run the function straight away.

// runs myFunction() immediately
button.addEventListener('click', myFunction());

So leave the parentheses off.

But what if you wish to pass a parameter to the function? Again adding parentheses will run the function immediately.

So to keep this as a callback function so it runs after the click event you could write:

// runs myFunction() immediately
button.addEventListener('click', () => myFunction(param));

This is now a callback function again.

(See video by Ania Kubow.)

Another way is where we declare the function in place:

button.addEventListener('click', function myFunction() {
    // some code to run ..
})

or with an arrow function:

button.addEventListener('click', () => {
    // some code to run ..
})

Passing a parameter

If you pass a parameter you can access many different things.

paramButton.addEventListener('click', (e) => {
    console.dir(e);
});

const whatId = document.getElementById('what-ID');

whatId.addEventListener('click', (e) => {
    alert(`This button has the following classes: ${e.target.classList}`);
    alert(`Using e.target.id the ID of this button is '${e.target.id}'`);
    alert(`Using e.type, the type of event, is '${e.type}'`);
});

You can use other things here instead of e.target.id such as .classList, e.target.style, e.offsetX, e.clientY etc..

Try holding down Shift, Control or Alt keys when pressing this button.

NB. shiftKey not shftKey.

keyTest.addEventListener('click', (e) => {
    if (e.altKey === true) {
        alert('You held down the alt key');
    } else if (e.ctrlKey === true) {
        alert('You pressed the control key');
    } else if (e.shiftKey === true) {
        alert ('You pressed the shift key');
    } else {
        alert('You didn\'t press a key.');
    };
});