DEV Community

benboorstein
benboorstein

Posted on

My Raw Notes for the Week of 8-23-2021

ENGLISH:

Holt: "Whatever you put into the DOM and whatever you get out of it are going to strings, every time."

Event Delegation/Bubbling.
Definition according to one guy (paraphrased):
A way to add an event listener once (on the parent) for multiple elements (children) with support for adding extra children later on.
Put another way:
You don't need to add an event listener for each child inside the parent. Instead just put it on the parent and it works for each child. And this also works when you add a new child through DOM manipulation (the whole createElement()... process).
An article recommended by Robert:
https://programmingwithmosh.com/javascript/javascript-event-bubbling-and-event-delegation/
Holt and JM say common interview question.

To basically understand how to use event.stopPropagation() (not practiced in code below), go here: https://www.youtube.com/watch?v=UWCvbwo9IRk.

CODE:

// HTML
<ul class="myList">
    <li>Apple</li>
    <li>Banana</li>
    <li>Carrot</li>
</ul>

// JS
const myList = document.querySelector('.myList')

// Point 1: Note that here you're putting the event listener on the PARENT of the elements you want to turn red upon click, and it works.
myList.addEventListener('click', function(e) {
    const target = e.target
    // FYI the 'matches' method returns a boolean (and here it evaluates to 'true', and we know this because each of the elements DOES turn red upon click)
    if (target.matches('li')) {
        target.style.backgroundColor = 'red'
    }
})

// Point 2: This NEW 'li' element ALSO turns red in the UI upon click. 
const newLi = document.createElement('li')
newLi.textContent = "Delegation"
myList.appendChild(newLi)

// The lesson: You don't need to add an event listener for each child inside the parent. Instead just put it on the parent and it works for each child.

//-------------------------------------------------------------------

// HTML
<div class="button-container">
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>
</div>

// JS
document.querySelector('.button-container').addEventListener('click', function(event) {
    // The below line is only here to disable being able to click on the parent element (div with class 'button-container') which then gives an alert that reads 'You clicked on button 1 2 3 4 5', which is not what we want.
    // Note also that 'BUTTON' has to be in all uppercase because that's what tagName returns.
    if (event.target.tagName === 'BUTTON') {
        alert(`You clicked on button ${event.target.innerText}`)
    }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)