I’m trying to have a button that when clicked the background position changes (and I don’t want to use CSS because I want it to stick, not just do it when clicked). Then when the user clicks a save button it checks the background position to see which setting to save (on or off). I am using jQuery and from what I have seen online it looks like I am getting everything right, but it isn’t working, so something isn’t right. Here is code:
function onoffButton(i, g)
{
$(i).click(function () {
if ($(g).css("backgroundPosition") == "0px -20px") {
$(g).css("backgroundPosition", "0px 0px");
} else {
$(g).css("backgroundPosition", "0px -20px");
}
});
}
Which would then be called by something like this:
onoffButton("#testswitchRating", "#faviconswitch");
And then to check them to save settings:
if ($("#ratingswitch").css("backgroundPosition") == "0px 0px") {
createCookie('showRatings', 0,365);
}
if ($("#ratingswitch").css("backgroundPosition") == "0px -20px") {
createCookie('showRatings', 1,365);
}
I’m reading the cookie here:
function checkSettings()
{
if (readCookie('showRatings') == 0) {
$('.rating').css('display', 'none');
$('#ratingswitch').css('background-position','0px 0px');
} else {
$('.rating').css('display', 'inline');
$('#ratingswitch').css('background-position','0px -20px');
}
}
Then I call it here:
<body onload="checkSettings();">
I think the best possible suggestion here is to simply use a CSS class like
.altPosition, and define the difference in your CSS file. Then usetoggleClass()like so:For saving your cookie, you can then just do something with
$(g).is(".altPosition")to detect which state it is in, andtoggleClass()can take a second parameter as a boolean for on or off for reading your cookies:And then in your css: