zelocalhost
zelocalhost

Reputation: 1183

Onclick doesn't work after remove/add class with jquery

I want to understand why this code work only with first onclick:

html:

    <div id="TheCarouselPlay">
        <button type="button" class="btn btn-warning btn-xs pause">
            <i class="fa fa-pause"></i>
        </button>
    </div>

js:

/* pause & play */
$('#TheCarouselPlay button.pause').click(function () {
    $('#TheCarouselPlay i').removeClass('fa-pause').addClass('fa-play');
    $(this).removeClass('pause').addClass('play');
});
$('#TheCarouselPlay button.play').click(function () {
    $('#TheCarouselPlay i').removeClass('fa-play').addClass('fa-pause');
    $(this).removeClass('play').addClass('pause');
});

http://jsfiddle.net/W59Me/4/

Upvotes: 0

Views: 865

Answers (4)

denizvatan
denizvatan

Reputation: 1

setTimeout function will do the trick. Here is an example:

    setTimeout(function(){
       $(this).removeClass('play').addClass('pause');
    }, 100);

Upvotes: 0

jamis0n
jamis0n

Reputation: 3820

This can be done with one button click handler, checking the current state based on which class the button currently has:

$('#TheCarouselPlay button').click(function () {
    if($(this).hasClass('play')){
      $('#TheCarouselPlay i').removeClass('fa-play').addClass('fa-pause');
      $(this).removeClass('play').addClass('pause');
    } else{
      $('#TheCarouselPlay i').removeClass('fa-pause').addClass('fa-play');
      $(this).removeClass('pause').addClass('play'); 
    }
});

Here is the fiddle: http://jsfiddle.net/gW2pn/

Upvotes: 2

Erick Monta&#241;ez
Erick Monta&#241;ez

Reputation: 447

You have to use on()

/* pause & play */
$('#TheCarouselPlay').on('click','button.pause',function () {
    $('#TheCarouselPlay i').removeClass('fa-pause').addClass('fa-play');
    $(this).removeClass('pause').addClass('play');
});
$('#TheCarouselPlay').on('click','button.play',function () {
    $('#TheCarouselPlay i').removeClass('fa-play').addClass('fa-pause');
    $(this).removeClass('play').addClass('pause');
});

Because button.play didn't exist when you defined the click event.

Upvotes: 1

Clayton
Clayton

Reputation: 444

Try using event handlers instead:

    /* pause & play */
$('#TheCarouselPlay').on('click', 'button.pause', function () {
    $('#TheCarouselPlay i').removeClass('fa-pause').addClass('fa-play');
    $(this).removeClass('pause').addClass('play');
});
$('#TheCarouselPlay').on('click', 'button.play', function () {
    $('#TheCarouselPlay i').removeClass('fa-play').addClass('fa-pause');
    $(this).removeClass('play').addClass('pause');
});

Here is the new fiddle: http://jsfiddle.net/xe79K/

Upvotes: 1

Related Questions