Reputation: 507
trying to change background images using css() method... not sure what is the best method to do this. I tried to copy, the first instance I am using toggle to change the switch image, and its working fine, it also changes the background image to day...
$('.switch').on('click', function(){
$('.night, .day').toggle();
$('body').css('background','url(img/day.jpg)');
}),
in the second instance is that I am having a problem, I want to switch back to the original night.jpg, but is not working..
$('.switch').on('click', function(){
$('body').css('background','url(img/night.jpg)');
})
Here is a somewhat working bin... jsbin
Upvotes: 1
Views: 87
Reputation: 171679
Combine both click handlers. If you use 2 of them they will both be triggered
A simple way to keep track of state would be to toggle a class on the switch
$('.switch').on('click', function(){
var isOn = $(this).hasClass('on');
var img = isOn ?'img/day.jpg' : 'img/night.jpg';
$('.night, .day').toggle(isOn);
$('body').css('background','url('+img+')');
$(this).toggleClass('on');
});
That being said the use of css for this would be far simpler and only requires toggling the class on body
Upvotes: 1
Reputation: 32921
I would toggle a .night
class on <body>
in this situation.
You can do like...
$('.switch').on('click', function () {
$('body').toggleClass('night');
});
Then in your CSS have something like:
body {
background-image: url('img/day.jpg');
}
body.night {
background-image: url('img/night.jpg');
}
Unless the value for a CSS property is dynamic it's much easier to handle it directly in CSS.
Upvotes: 4