Question

I'm admittedly completely unfamiliar with jQuery. I've snooped around here a bit trying to find snippets to help me accomplish my goal, and I can't find anything.

My markup is such:

<a href="#" id="local-song-button" class="music sm2_link">
    <i id="button-toggle" class="fa fa-play-circle-o blue"></i>
</a>

I'm running a script that changes the local-song-button <a> depending on the event. It can be sm2_link for an inactive song playing, sm2_playing while a song is playing and sm2_paused when paused.

Now, the problem I'm running into is I'd like to change the class of button-toggle depending on which class the local-song-button is taking. I can't seem to figure out the correct way to do this. I've looked into toggleClass() as well but I feel like I'll need an if() statement somewhere? This is all I could come up with:

if ($('#local-song-button').hasClass('sm2_playing')){
   $('#button-toggle').removeClass('fa-play-circle-o');
   $('#button-toggle').addClass('fa-pause');
}elseif ($('#local-song-button').hasClass('sm2_paused')){
   $('#button-toggle').removeClass('fa-pause');
   $('#button-toggle').addClass('fa-play-circle-o');
}

And that's definitely not working.

Was it helpful?

Solution

This should work, you missed the space in between else and if, you could also use toggleClass.

function togglePlayButton()
{
    var loadingBtn = $('#local-song-button');
    var toggleBtn = $('#button-toggle');

    if(loadingBtn.hasClass('sm2_playing') || loadingBtn.hasClass('sm2_link'))
    {
      toggleBtn.toggleClass('fa-play-circle-o fa-pause');
    }
    else if(loadingBtn.hasClass('sm2_paused'))
    {
      toggleBtn.toggleClass('fa-pause fa-play-circle-o');
    }
}

OTHER TIPS

If you use firebug or chrome developer tools, you can see this error from the console tab:

Uncaught SyntaxError: Unexpected token { 

It's because of your elseif. The correct way is to use else if. Fix it and it should be fine.

Also note that from the provided HTML markup in your question, the #local-song-button anchor only has class sm2_link, not either sm2_playing or sm2_paused

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top