Flash Flash - 3 months ago 12
jQuery Question

Dynamically change jQuery "hover" by checking cookie

How can I change the function within a jQuery

.hover()
by checking a users cookie?

Right now the code works when the site first loads, but when the cookie is updated (through javascript) the
.hover()
does not switch unless the page is reloaded:

var SkinChk = getCookie('skincookie');

$('.fadeMenu').hover(function(){
if (SkinChk == 'Alternative') {
// Alternative Skin
$(this).stop().animate({ backgroundColor:'rgb(66, 137,170)', color:'#F7F9F4'},500);
} else {
// Default Skin
$(this).stop().animate({ backgroundColor:'rgb(255,165,0)', color:'#FFFFFF'},500);
}
}, function(){
if (SkinChk == 'Alternative') {
// Alternative Skin
$(this).stop().animate({ backgroundColor:'rgb(247, 249, 244)', color:'#1F262A'},500);
} else {
// Default Skin
$(this).stop().animate({ backgroundColor:'rgb(201,224,179)', color:'#333333'},500);
}
});


The
var SkinChk = getCookie('skincookie');
references a working javascript function I didn't post for brevity. It returns the cookie value.

Answer

Well, you're only checking the cookie once, so there's nothing to tell the function to update the SkinChk variable.

The easiest way to fix that would be to move the cookie check inside the hover function:

var SkinChk;    

$('.fadeMenu').hover(function(){
    //Check if the cookie has changed
    SkinChk = getCookie('skincookie');
    if (SkinChk == 'Alternative') {
        // Alternative Skin
        $(this).stop().animate({ backgroundColor:'rgb(66, 137,170)', color:'#F7F9F4'},500);
    } else {
        // Default Skin
        $(this).stop().animate({ backgroundColor:'rgb(255,165,0)', color:'#FFFFFF'},500);
    }
}, function(){
    //Check if cookie has changed
    SkinChk = getCookie('skincookie');
    if (SkinChk == 'Alternative') {
        // Alternative Skin
        $(this).stop().animate({ backgroundColor:'rgb(247, 249, 244)', color:'#1F262A'},500);
    } else {
        // Default Skin
        $(this).stop().animate({ backgroundColor:'rgb(201,224,179)', color:'#333333'},500);
    }
});

You could also create an event that listens to a service which monitors the cookie. Check out nsICookieService. I wouldn't reccomend it, though, because it seems like massive overkill for what you're trying to do, but it is an option.

Comments