0

I'm looking for two days on how to add an eventListener on each div in my Nodelist. I'm working with an API for school and we have to display movies and they need to be edited, liked and more so i had the idea to put a "see more" button on movies posters to display buttons and more informations. Here is my code:

const movieIntegration =() => {
    allMovies.map(movie=> {
        movieGallery.innerHTML += `<div class="imgContainer">
                                        <img src="${movie.img}" alt="${movie.name}">
                                                <div class="titleContainer">
                                                    <div class="movieTitle"> ${movie.name} </div>
                                                    <div class="seemore"> See more </div>
                                                </div>
                                    </div>`
    })

const seemore = document.querySelectorAll(".seemore")
    seemore.forEach(elm => {
        elm.addEventListener("click", console.log("this is working"), true)
    })

}

Now I need to get all the divs with a "seemore" class (it returns a NodeList) and add an eventListener that works on click but when I do it and then console.log a message on click, my console displays nine times the message but I havent clicked on the buttons and then, when I click on them, nothing happens.

Can someone help me please ?

(ps: Sorry if you misunderstand, I am bad in English)

Saantuu
  • 31
  • 7
  • `console.log(`…`)` is not a function. `addEventListener` expects functions. Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Dec 05 '21 at 19:59
  • I read the MDN Web Doc about event delegation but I don't know if I understand what it is, but I'm going to take a closer look at it when I have a little more times, thanks :) – Saantuu Dec 05 '21 at 20:24

1 Answers1

0

You code is not working because you using are the return value of console.log as the listener. If you want the listener to be function that calls console.log use the following syntax

elm.addEventListener("click", () => console.log("this is working"), true)
Sherif Elmetainy
  • 4,034
  • 1
  • 13
  • 22
  • thank you so much, I already tried this yesterday and it wasn't working, I think it was because "true" was missing but you perfectly answered my question, thank you :) – Saantuu Dec 05 '21 at 20:25