Search code examples
jquerytoggleclass

Adding event on JQuery toggled class


My markup:

<ul id="playerControls">
    <li class="play-bt"></li>
</ul>

And I have this event that fires if the play button is pressed:

$(".play-bt").bind('click',function(){
    $(this).toggleClass('pause-bt');
});

Now I am assuming that play-bt class name has been changed to pause-bt, but how come this event:

$(".pause-bt").bind('click',function(){
    console.log('PEW');
});

Is not being fired?


Solution

  • Now I am assuming that .play-bt class name has been changed to pause-bt.

    toggleClass doesn't work like that.

    toggleClass is the combination of addClass and removeClass.

    toggleClass will check whether the specified class exists.

    • If it does, it removes it from the element.
    • If it doesn't, it adds it to the element.

    Regarding the reason your event does not fire, this is because you must have binded that click event before assigning the class pause-bt.

    bind() searches for all elements which match the selector, at that current point, and assigns the function to the event handler.

    You need to either rebind this event, or use live() instead of bind()

    live():

    Attach an event handler for all elements which match the current selector, now and in the future.

    http://api.jquery.com/live/