Graphicd02
Graphicd02

Reputation: 73

Toggle background-image on click with jQuery. Multiple events

I have a list of songs that have play buttons attached to them. With the code below, I am able to switch the "play" button to "pause" when clicked and if another "play" link is clicked the original song switches back to "Play" and the newly clicked track shows "Pause" as it should.

HOWEVER, when I click a track that is playing and the button changes to "Pause", pressing it again doesn't switch it back to "Play".

Basically I would like the image to toggle on click and if another button is pushed the first button reverts back to it's original state.

Any help would be greatly appreciated!

$(function() {
    $('.play').click(function () {

       $('.play').css('background-image', 'url(My Play Button URL)');


       $(this).css('background-image', 'url(My Pause Button URL)');


    });
    });

Upvotes: 1

Views: 5797

Answers (2)

UbiQue
UbiQue

Reputation: 1571

A little bit faster and simplier code snippet inspired by Arun P Johny:

$('.play').click(function ()
{
    return $(this).is('.playing')
    ?
        $(this).css('background-image', 'url(My Play Button URL)').removeClass('playing')
    :
        $(this).css('background-image', 'url(My Pause Button URL)').addClass('playing')
    ;
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use a class to check the current status

$(function() {
$('.play').click(function () {

   $('.play').not(this).css('background-image', 'url(My Play Button URL)').removeClass('playing');

    if(!$(this).is('.playing')){
       $(this).css('background-image', 'url(My Pause Button URL)').addClass('playing');
    }


});
});

Fiddle: http://jsfiddle.net/arunpjohny/7a4ua/

Upvotes: 1

Related Questions