Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eventListener firing multiple times and increasing

On a click function I have the option of playing audio.

The click is only fired once (after I added .off(), which I seem to have to do for every click event because I think there's something I fundamentally don't get about how javascript works) but the function added to the "ended" listener shows it is firing the number of times the button has been clicked. I presume .play() is also being fired multiple times.

These need to be inside the click event to get the id so how do I stop these kinds of things from happening, here and elsewhere when using js? Adding event.stopPropagation(), event.bubbles = false and .off() everywhere seems unnecessary (and in this case doesn't make a difference anyway).

$('.button').off().on('click', function(event){
    event.stopPropagation();
    event.bubbles = false;
    var id = $(this).attr('id')
    if ($(this).hasClass('hasAudio')) {
        document.getElementById('audio_'+id).play();
        document.getElementById('audio_'+id).addEventListener("ended", function(){
            console.log("ended");
        });
    }
});
like image 797
MikeyB Avatar asked Dec 18 '17 10:12

MikeyB


People also ask

Why is event listener firing multiple times?

This symptom is indicative that you've registered the same listener more than once. You must remember to deregister events when your component unloads to prevent his problem.

How do you make Eventlistener work only once?

Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.

Can a button have multiple event listeners?

An event listener is added to an element on the page, such as a button. The event listener will invoke a specified function when the event triggers. Javascript supports multiple functions on a single event, as well as multiple event listeners for a single element.

What happens if you add the same event listener twice?

If the same event listener function is registered twice on the same node with the same type and useCapture arguments, the second registration is simply ignored. ...


1 Answers

Move the ended event outside the click event,you are registering the event each time you click on the button

$('.button').on('click', function(event){
    var id = $(this).attr('id')
    if ($(this).hasClass('hasAudio')) {
        document.getElementById('audio_'+id).play();

    }
});
$('[id^="audio_"]').on("ended", function(){
    console.log("ended");
 });
like image 196
madalinivascu Avatar answered Sep 30 '22 17:09

madalinivascu