1
votes

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)');


    });
    });
2
Because you are setting the clicked button to always playing mode. You need to check whether a button is currently playing and based on that you need to set the styleArun P Johny
Thanks for the quick response! In your Fiddle, when I click track 1 and then click it again, it stays blue. How would I get it to switch back to red once clicked again?Graphicd02
I guess what I mean, is how to toggle that play/pause function.Graphicd02
One last question...I'm not sure if you're familiar with the Souncloud Stratus player, but that is what I'm using. Would there be any way to change the image back to it's default state once the track has finished playing? I owe you a beer! Stratus: stratus.scGraphicd02

2 Answers

1
votes

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/

0
votes

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')
    ;
});