I've looked around for an answer and nothing works for me. I want to be able to click a div and have the background change, then on the next click of the div I want it to change back again. The first part works, however I cannot figure out how to do the second part.
This is what works (using jQuery):
$(document).ready(function(){
$('.button').click(function() {
$('.icon').css("background-position", "0px 0px");
});
});
Any help would be appreciated, thanks.
I've looked around for an answer and nothing works for me. I want to be able to click a div and have the background change, then on the next click of the div I want it to change back again. The first part works, however I cannot figure out how to do the second part.
This is what works (using jQuery):
$(document).ready(function(){
$('.button').click(function() {
$('.icon').css("background-position", "0px 0px");
});
});
Any help would be appreciated, thanks.
Share Improve this question asked Apr 6, 2012 at 8:58 AnarcheiAnarchei 31 silver badge2 bronze badges3 Answers
Reset to default 5Rather than use the .css method, I remend using .toggleClass and put the relevant css into a class:
$('.icon').toggleClass('myClass');
your class definition:
.myClass { background-position: 0px 0px };
The .toggleClass method will add the class if it's not already present or remove it if it is.
I agree with reendations to use .toggleClass()
, but if you want to use .css()
try this:
$(document).ready(function(){
$('.icon').each(function(){
$(this).data('default-bg-pos', $(this).css('background-position'));
$(this).data('state', 0);
});
$('.button').click(function() {
$('.icon').each(function(){
if ($(this).data('state')) {
$(this).data('state', 0);
$(this).css('background-position', $(this).data('default-bg-pos'));
} else {
$(this).data('state', 1);
$(this).css("background-position", "0px 0px");
}
});
});
});
You should use a css class and toggle it.
.zero{
background-position: "0px 0px";
}
$(document).ready(function(){
$('.button').click(function() {
$('.icon').toggleClass("zero")
});
});