Home > Software design >  Eventlistener accumulating and functioning more than once when activated (JavaScript)
Eventlistener accumulating and functioning more than once when activated (JavaScript)

Time:11-14

I am trying to create a to do list, currently I just want a button to add and remove tasks.

The add buttons add a new task and a button attached to it.

For the time being the button attached only prints "hello", however I am noticing that more than 1 hello is being printed when there are multiple tasks.

I imagine this is because the eventListeners are accumulating to the oldest tasks. This happens due to the for loop created to add this eventListeners.

I thought a easy solution to add the eventListeners was to place the for loop outside the add() function but I was not able to get that working.

How can I stop the eventListeners from accumulating?

const addBtn = document.getElementById("add-btn")
const divWrp = document.getElementById("wrapper")
let tasks = document.querySelectorAll('.task')
let closeBtns = document.querySelectorAll('.close-btn')
let a = 1;
let b = 0;

addBtn.addEventListener("click", function(){
    let newTask = document.createElement("div")
    newTask.classList.add("task")
    newTask.textContent = "Task"   a
    let closeBtn = document.createElement("button")
    closeBtn.classList.add("close-btn")
    newTask.append(closeBtn)
    divWrp.append(newTask)
    
    console.log(newTask)
    a  = 1;

    closeBtns = document.querySelectorAll('.close-btn')
    console.log(tasks.length)
    
    for (let i = 0; i < closeBtns.length; i  ){
        closeBtns[i].addEventListener("click", function(){
            b  = 1
            console.log("hello world"   b)
        })
    }
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="add-btn">ADD</button>
    <div id="wrapper"></div>

    <script src="index.js"></script>
    <script src="jquery-3.6.1.min.js"></script>
</body>
</html>

CodePudding user response:

You can just directly attach the event handler to the element you just created. Replace the loop with

closeBtn.addEventListener("click", function(){
  console.log("hello world")
  // I guess you want something like this here:
  // newTask.remove()
})
  • Related