3

How do we add an event listener on each item of the code only once, it's easy to do state management in the react but how do we do this in plain old javascript

     <div class="grid-container" id="ad">
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>   
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      </div>


   let divs = document.querySelectorAll(".grid-item")

        for(let i=0;i<divs.length;i++) { 

            divs[i].addEventListener("click", function() {
            divs[i].style["background-color"] = "red";

        });
    }
2
  • There is no text or nothing inside the grid-item, then where exactly you will handle the click?? Commented Feb 29, 2020 at 8:14
  • remove eventListener on the clicked div.grid-item or from all div.grid-item? Commented Feb 29, 2020 at 8:16

2 Answers 2

3

You need to use a named function rather than an anonymous one. And then use that named function to remove all listeners, in the same way you added them.

Here's a jsfiddle example: https://jsfiddle.net/v1akgpL6/

let divs = document.querySelectorAll(".grid-item");

/* Remove all event listeners */
const removeListeners = () => {
    for (let j = 0; j < divs.length; j++) { 
    divs[j].removeEventListener("click", clickHandler);
  }
}

/* Click event listener */
const clickHandler = (e) => {
  e.currentTarget.style["background-color"] = "red";
  removeListeners();
}

/* Add event listeners */
for (let i = 0; i < divs.length; i++) {
    divs[i].addEventListener("click", clickHandler);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the options object in the event listener to make the event happen just once like this:

let divs = document.querySelectorAll(".grid-item");
const changeBackgroundColor = e => {
 e.target.style.backgroundColor = "red";
 }
divs.forEach(div => {
 div.addEventListener("click", changeBackgroundColor, {once: true});
})

2 Comments

How can I return the divs i'th value where I had clicked?
you can use e.target.value or e.currentTarget.value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.