Erurainion
Erurainion

Reputation: 113

Check/Change Background position

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();">

Upvotes: 0

Views: 722

Answers (1)

gnarf
gnarf

Reputation: 106332

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 use toggleClass() like so:

$(i).click(function () {
    $(g).toggleClass("altPosition");
});

For saving your cookie, you can then just do something with $(g).is(".altPosition") to detect which state it is in, and toggleClass() can take a second parameter as a boolean for on or off for reading your cookies:

// to write:
createCookie("showRatings", $("#ratingsswitch").is(".altPosition"), 365);
// and to read:
$("#ratingsswitch").toggleClass("altPosition", readcookie("showRatings"));

And then in your css:

#faviconswitch { 
    background-position: 0px 0px;
}
#faviconswitch.altPosition { 
    background-position: 0px -20px;
}

Upvotes: 2

Related Questions