Events

Page section: posts

Events

Events can consist of many different things but the most common is typically a mouse click. Others include keyboard strokes, the completion of the page loading, scrolling, mouse hovers etc..

inline event handler

All lowercase onclick="...", this is actually an HTML attribute that can contain some javascript.

<button onclick="alert('this is from an onclick event')">Click me</button>

To reset the style tag it was simply removed with removeAttribute.

buttons1[3].addEventListener('click', () => {
    document.body.removeAttribute('style');
});

event handler property

Instead of using the the HTML attribute on the element itself this time you add it in the javascript.

myButton.onclick = blue;

Full code:

function blue() {
    document.body.style.background = '#137';
};

const myButton = document.getElementById('my-button');

myButton.onclick = blue;

These are not particularly useful and a little weird in that you omit the brackets when calling a function:

btn.onclick = blue();
btn.onclick = blue;

You can’t just add an alert to these: myButton.onclick = alert() won’t work with or without the parentheses. Instead you store your alert in a variable:

const myAlert = () => { alert('My alert message')};
// then call myAlert like so
btn.onclick = myAlert;

Note that when passing a function reference to the onclick property, we do not include parentheses, as we are not invoking the function in that moment, but only passing a reference to it

Tania Rascia on Digital Ocean

event listeners

These are the modern and preferred way to both of the above methods. At first they may seem a bit more complicated and verbose but as soon as you start using them with more than one element, say multiple buttons, the advantages become much clearer.

Event listeners have two mandatory parameters:

  1. the event being listened for, eg. click
  2. the listener callback function

 const testEl = document.getElementsByClassName('evnt-lstnrs');
 const elText = document.getElementById('el-text');

 testEl[0].addEventListener('click', () => {
     elText.innerHTML = "Some text has been added to this empty paragraph"
     elText.removeAttribute('style');
 });

 testEl[1].addEventListener('click', () => {
     elText.innerHTML = "Some other text has been added in green";
     elText.style.color = '#070';
 });

See the console to see what is in (e)
See the console to see what is in (e.target)

The target property is one of the most important as this is what the click event happens on.

NB. You can also just add a named function to an event listener but you must omit the usual brackets. This is because if they’re not omitted the function will run straight away, before the event that is supposed to trigger it.

const clickHandler = () => {
    headingEl.style.color = 'red';
}

headingEl.addEventListener('click', clickHandler);

Capturing and bubbling

This applies to nested elements. The capture phase happens first though by default it is turned off. However when capture = true Javascript will select the outermost

Each <div> has it’s own event listener which simply logs it’s name to the console.

When the center <div> is clicked all 3 divs are clicked because the centre one is inside both of the outer divs. The order at which each fires is determined by bubbling. The inner one fires first, then it’s parent then finally the outer one. This is known as bubbling or event bubbling. So bubbling goes from the inside and works outward while capturing does the reverse.

Below the code has capture: true.

const grandparent = document.getElementById('grandparent');
grandparent.addEventListener('click', e => {
    console.log('Grandparent 1');
}, {capture: true })

const parent = document.getElementById('parent');
parent.addEventListener('click', e => {
    console.log('Parent 1');
}, {capture: true})

const child = document.getElementById('child');
child.addEventListener('click', e => {
    console.log('Child 1');
}, {capture: true})

To prevent the capturing or bubbling occuring you can add the stopPropagation() method.

const child = document.getElementById('child');
child.addEventListener('click', e => {
    console.log('Child 1');
    e.stopPropagation();
})

Running an event once

It’s also possible to allow an event to work just once using a third parameter again with once: true.

const child = document.getElementById('child');
child.addEventListener('click', e => {
    console.log('Child 1');
}, {once: true})

You can also remove the event listener after a certain time:

setTimeout{() => {
    parent.removeEventListener('click', functionName)
}, 2000)

NB. The time, 2000 is in milliseconds.

Event delegation

@ 13m 17s yt

Event target

mackeral

flounder

halibut

Event listener change

Type in the box then press enter, tab or click anywhere outside the box.

This uses the change event like so:

const changeInput = document.querySelector('#change-input');

changeInput.addEventListener('change', e => {
    document.querySelector('#change-div').textContent = e.target.value;
})

The change event works differently on different elements. Here, on an <input type="text"> it fires when the value has changed AND it loses focus.

  1. Understanding events in JS by Tania Rascia.
  2. Event Delegation

Table of Contents