Search code examples
javascriptevent-delegation

Event delegation problems


I'm learning javascript and having trouble with event delegation. I was testing what I have completed in the browser for errors--not much--and keep getting a message back saying:

thumbs.addEventListener is not a function

Any help would be appreciated.

Here is my code:

window.addEventListener("load", function() {
    var thumbs = document.querySelectorAll("#thumbnails");
    thumbs.addEventListener("click", function(e) {
             
    });
});
<div id="thumbnails">
    <img src="http://via.placeholder.com/350x150?text=Battle" title="Battle" />
    <img src="http://via.placeholder.com/350x150?text=Luneburg" title="Luneburg" />
    <img src="http://via.placeholder.com/350x150?text=Bermuda" title="Bermuda" />
    <img src="http://via.placeholder.com/350x150?text=Athens" title="Athens" />
    <img src="http://via.placeholder.com/350x150?text=Florence" title="Florence" />
</div> 


Solution

  • Note: You're getting the error because you're calling addEventListener on the return value of querySelectorAll which is a NodeList that doesn't have a function called addEventListener. Use querySelector instead of querySelectorAll.


    To achieve event delegation, you'll have to set the event listener on one of the ancestors of your elements (for example #thumbnails), then when the click happens, check if the target of the event is an image:

    var container = document.querySelector("#thumbnails");        // select the ancestor, use querySelector instead of querySelectorAll
    
    container.addEventListener("click", function(event) {         // add the click event listener to it
        var target = event.target;                                // when the click happens, get the target of the click
        if(target.matches("img")) {                               // check if the target is one of our img (the selector passed to "matches" could be any css selector, for example "#thumbnails > img", ...)
            console.log(target.title);                            // use the element, or whatever
        }
    });
    

    Example:

    var container = document.querySelector("#thumbnails");
    
    container.addEventListener("click", function(event) {
        var target = event.target;
        if(target.matches("img")) {
            console.log(target.title);
        }
    });
    <div id="thumbnails">
        <img src="http://via.placeholder.com/350x150?text=Battle" title="Battle" />
        <img src="http://via.placeholder.com/350x150?text=Luneburg" title="Luneburg" />
        <img src="http://via.placeholder.com/350x150?text=Bermuda" title="Bermuda" />
        <img src="http://via.placeholder.com/350x150?text=Athens" title="Athens" />
        <img src="http://via.placeholder.com/350x150?text=Florence" title="Florence" />
    </div>