0

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)
      }
    })
  })
cpvd
  • 3
  • 2
  • `button.addEventListener("click", function removeFavourites() {`…`});` binds the second event listener unconditionally. It doesn’t depend on `click` or anything else. So a single click invokes both event listeners. I would suggest using [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead. Bind _one_ event listener and check the state inside. See [the tag info](/tags/event-delegation/info) and [this Q&A](/a/34896387/4642212). – Sebastian Simon Jan 01 '23 at 13:36

1 Answers1

0

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

DSDmark
  • 1,045
  • 5
  • 11
  • 25