JordyvD
JordyvD

Reputation: 1615

Delegated event triggering even when it shouldn't

I have the following code:

 // Define controls
$('.play-video').click(function(){
    // Get the video element
    var video = $(this).parent().parent().find('video');
    // Play the video
    $(video).get(0).play()

    // Remove the play class and add the pause class so the same button will pause the video
    $(this).removeClass('play-video');
    $(this).addClass('pause-video');

    // Set pause text
    $(this).text('Pause');
});



$(document).on('click','.pause-video',function(){
    console.log('pausing...');
    // Get the video element
    var video = $(this).parent().parent().find('video');
    // Play the video
    $(video).get(0).pause()

    // Remove the play class and add the pause class so the same button will pause the video
    $(this).removeClass('pause-video');
    $(this).addClass('play-video');

    // Set pause text
    $(this).text('Play');
});

Problem is, that the second click event should trigger on

.pause-video
only but also triggers on
.play-video

Question is: What did I do wrong?

Thanks in advance, G3

Upvotes: 1

Views: 59

Answers (4)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Your code is close. but your first event handler also needs to be delegated too:

$(document).on('click', '.play-video', click(function(){

Upvotes: 2

Balázs Varga
Balázs Varga

Reputation: 1856

The problem is that jQuery can't track object changes on the fly. Just use one click event, and determine what to do inside this:

$('.play-stop-video').click(function(){
    if($(this).hasClass('play')) {
        // Current play button code here....
    }
    if($(this).hasClass('stop')) {
        // Current stop button code here....
    }
    $(this).toggleClass('play').toggleClass('stop');
});

$(something).click( ... will runs when the page loads, and attach the click events to the play and stop buttons. However, you don't have any stop buttons at this time, so the click event for this will be discarded...

Upvotes: -1

syms
syms

Reputation: 411

try to stop immediage propagation $('.play-video').click

Upvotes: 1

Pointy
Pointy

Reputation: 413709

You've attached the "play" event handler directly to the button instead of using delegation. That handler will continue to fire because of that, even if you change the class.

Delegation works through event bubbling, and the selector you pass in to the .on() call is re-examined with every event. That is not the case with handlers that are directly attached: once those are active, they're active until they're removed or until the DOM element itself is removed. Changing the particulars of the DOM element won't make a difference.

Your problem can therefore be solved by using delegation for both cases.

Upvotes: 2

Related Questions