Home > OS >  why is my eventListener called multiple times
why is my eventListener called multiple times

Time:08-20

function form_anim(){

    form_2.style.transform = "translateX(0)"
    form_2.style.transition = "transform 400ms"
}
previous.addEventListener('click',()=>{

    form_2.style.transform = "translateX(900px)";
    form_2.style.transition = "transform 400ms"
    form_holder.classList.toggle('anim2');
})

//let n = 1;

submit_1.addEventListener('click',()=>{

    //n=1;

    form_holder.classList.toggle('anim');
    form_holder.addEventListener('animationend',()=>{

       
        form_2.style.transform = "translateX(0)"
        form_2.style.transition = "transform 200ms"

    })
});

I am trying to create 3 forms each has the next and previous buttons. When the next button is clicked, the first form should scale to 0, and form 2 should translate X(0px), initially set as 900px. It works the first time perfectly but when the previous is clicked the 2nd form translates to 900px but then comes back to 0px.

CodePudding user response:

You should not add a new event listener every time when submit_1 button is clicked. When you click the button second time the event listener added on the first click will also run
Try using this code:

form_holder.addEventListener('animationend',()=>{
        form_2.style.transform = "translateX(0)"
        form_2.style.transition = "transform 200ms"
});

function form_anim(){
    form_2.style.transform = "translateX(0)"
    form_2.style.transition = "transform 400ms"
}
previous.addEventListener('click',()=>{

    form_2.style.transform = "translateX(900px)";
    form_2.style.transition = "transform 400ms"
    form_holder.classList.toggle('anim2');
})

//let n = 1;

submit_1.addEventListener('click',()=>{
    //n=1;
    form_holder.classList.toggle('anim');
});

CodePudding user response:

I found that adding RemoveEventlsitener inside the form_holder function works well thank you all for spending your valuable time trying to answer my question.

  • Related