2

I'm still quite new to this so please bear with me. I have a function which adds a class on a click event, this works fine. But I would also like the clicked function to be saved as a cookie so when that user next visits the site those classes are still there/reapplied. I'm using jquery.cookie for this. My code is as follows.

$(".bblue").click(function bblue() {
    $("dl").addClass("bbluebg");
    $("dd .button").addClass("buttonb");
    $('.button img').attr('src',function(i,e){return e.replace("White","DBlue");});
    $.cookie("color", function bblue(){} , { expires: null, path: '/' });
});

When I call $.cookie('color'); is returns function bblue(){} but it doesn't run the function when the page loads next.

2 Answers 2

5

I assume you want to store the preference and take action based on that. Try something like this:

// Event-independent color change function
var bblue = function() {
    $("dl").addClass("bbluebg");
    $("dd .button").addClass("buttonb");
    $('.button img').attr('src', $('.button img').replace("White","DBlue"));
}

// Click action
$(".bblue").click(function () {
    // Change the color
    bblue();
    // Store the preference
    $.cookie("color", "blue" , { expires: null, path: '/' });
});

// On page load
$(document).load(function() {
    // If they chose blue before, change the color
    if ($.cookie("color") == "blue") bblue();
});    
0
1

The function isn't running again because the user isn't clicking anything when the page reloads. Your function only runs when someone clicks the .bblue element.

You need to get the value of the cookie and set classes where appropriate on document ready instead. The classes won't stick, you have to re-apply them. You want to use...

$(function() {
    var color = $.cookie("color");

    // Set classes according to color here
});

Which will execute and set all the classes once the page is loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.