JavaScript 30- Day 25 Study Notes

https://javascript30.com/

Day 25 of JavaScript 30 by Wes Bos worked on event listener concepts and introduced “once”.

We started with three nested divs, selected them, and console logged the event.

const divs = document.querySelectorAll('div');function logText(e){   console.log(this.classList.value);
}

If you click on the innermost div, all three divs will log a click event. This is because of “bubbling” where the click event will ripple up through the entire document including each nested div.

The event “capture” by the browser, starts from the outermost container and captures the event working inward to the innermost container. Then, the triggering of the event happens working outward from the innermost container going outward (bubbling).

The addEventListener method contains a capture argument.

divs.forEach(div => div.addEventListener('click', logText, {   capture:false}

False is the default setting.

divs.forEach(div => div.addEventListener('click', logText, {capture:true }

If we set the capture to true, the first capture triggers the event, that is, from the outermost container first.

If we run the stopPropagation method, only clicking on the innermost container will trigger a click event.

e.stopPropagation();

Finally, Bos introduced the “once” concept.

divs.forEach(div => div.addEventListener('click', logText, {   capture:false   once: true;}));

The eventListener method hears a click event and then unbinds itself so further click events are not recorded. That way the user can only click on the element once. This feature is useful in an online store checkout app where you only want the user to click on a button one time.

Interesting concepts covered today that should prove useful in future applications.

Follow my study notes as I progress through JavaScript 30.

Retired physician, writer, aspiring website designer and developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store