dhwind
dhwind

Reputation: 127

Function works more times, than needs

I have dynamically created elements. In vanilla JS we can communicate with such elements only with document.addEventListener('click',function(){//do smth});. So I have a script, which takes dynamically created buttons and adds event listener for them.

Problem is when I press some button one time, it's ok, but then script starts to count clicks and do code in btn.addEventListener('click', function(){ //do smth }); according to count of clicks. For example, I click 1 time - script makes 1 time, I click 2 times - script makes 3 times, I click 3 times - script makes 6 times, cause he counted all clicks. How can I resolve this problem?

document.addEventListener('click', addInCart);

function addInCart(){
    
    const productBtns = document.querySelectorAll('.product__btn');
    for(let btn of productBtns){
        btn.addEventListener('click', function(){
            //do smth
        });
    }
}

Upvotes: 0

Views: 91

Answers (2)

Refat Alsakka
Refat Alsakka

Reputation: 561

Because each time you click on the document will recall the function again, add {once: true} to avoid that.

document.addEventListener('click', addInCart, {once: true});

function addInCart(){

    const productBtns = document.querySelectorAll('.product__btn');
    for(let btn of productBtns){
        btn.addEventListener('click', function(){
            //do smth
        });
    }
}

Upvotes: 2

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

use .onclick = function() { ... } instead of .addEventListener('click', function() { ... })

document.addEventListener('click', addInCart);

function addInCart(){

    const productBtns = document.querySelectorAll('.product__btn');
    for(let btn of productBtns){
        btn.onclick = function(){
            //do smth
        };
    }
}

Upvotes: 1

Related Questions