Andy James Andy James - 5 months ago 11
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('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/intro-bg.jpg') 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
document.body.style.background = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/intro-bg.jpg') no-repeat center center fixed";
$("body").css({backgroundSize: "cover"});
audioElement.pause();
} else {
// Start playing
if (!initDone) {
initDone = true;
document.body.style.background = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/header-background.jpg') no-repeat center center fixed";
audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/om_cut.mp3');

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

audioElement.play();
}

$(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 ?

Answer

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 document.body.style.background =... above the condition and it should do what you're looking for.

Comments