javascriptaddeventlistenerremoveeventlistener

change listener on 2nd click


I have a javascript code where I store an element in an array upon clicking on a button, and change the button from "+" to "-". Upon clicking the button again, I want to remove that element from the array.

I have this code. It does the first part well, but it also removes the element without clicking on the button the second time.

let favorites = []
let buttonList = document.querySelectorAll("button")

let click = 0

  buttonList.forEach((button, index) => {
    button.addEventListener('click', function saveFavourites() {
      click++
      favorites.push(products[index])
      button.textContent = "-"
      console.log(favorites)
      if (click === 1) {
        this.removeEventListener('click', saveFavourites)
      }
    })
    button.addEventListener('click', function removeFavourites() {
      click ++
      let i = favorites.indexOf(products[index])
      favorites.splice(i, 1)
      button.textContent = "+"
      console.log(favorites)
      if (click === 2) {
        this.removeEventListener('click', removeFavourites)
      }
    })
  })

Solution

  • You're adding two separate event listeners to the same button element. Use a single event listener and toggle a boolean flag variable to keep track of whether the element should be added or removed.

    let favorites = []
    let buttonList = document.querySelectorAll("button")
    
    buttonList.forEach((button, index) => {
      let isAdded = false; // flag variable to track whether the element is added or removed
    
      button.addEventListener('click', function toggleFavourites() {
        if (isAdded) {
          let i = favorites.indexOf(products[index])
          favorites.splice(i, 1)
          button.textContent = "+"
          isAdded = false;
        } else {
          favorites.push(products[index])
          button.textContent = "-"
          isAdded = true;
        }
        console.log(favorites)
      })
    })
    

    When the button is clicked, the code checks the value of isAdded and either adds the element to the favorites array or removes it.

    Here is the Demo:- Codesandbox