Andy James Andy James - 4 months ago 8x
CSS Question

Change image on icon state change:Jquery

I am trying to change the "body" background image file on my webpage,when the user toggles between music icon play and pause.

Here is what the CSS for "body" element looks like :

body {
background: url('') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;

So in music function, I have two states, play and pause. I tried to change the image in each of the "if" conditions like this :

$("#music").click(function() {
if (playing) {
// Stop playing = "url('') no-repeat center center fixed";
$("body").css({backgroundSize: "cover"});
} else {
// Start playing
if (!initDone) {
initDone = true; = "url('') no-repeat center center fixed";
audioElement = document.createElement('audio');
audioElement.setAttribute('src', '');

audioElement.addEventListener('ended', function() {
this.currentTime = 0;;
}, false);

$(this).find('i').toggleClass('fa-music fa-stop');
playing = !playing;

Now what happens is that when I play the music, the image changes and then when I click the stop icon the image again changes back to my regular image. But then the next time I click play again the image does not change. So it means what I did only gets executed once. How can I make it to happen every time I toggle between the play and pause ?


The first time through, you are setting this initDone = true;

So, on the second and successive calls the if (!initDone) condition prevents the image from changing.

Move =... above the condition and it should do what you're looking for.