0

I'm using the jquery cookie plugin and I'm trying to have the browser remember the state of a CSS after a refresh, here's my code when a button is clicked:

    $('#cartHolder').attr('style','display: none !important');
    $.cookie("cartDisplay", 'none !important');

Then in my header I have:

   if ($.cookie("cartDisplay")){
       $('#cartHolder').attr('style', $.cookie("cartDisplay"));
   }

The problem is, after each refresh the displayproperty is still reset back to it's default property. However in the console window I see that jquery cookie has successfully stored the necessary value, it's just not being written into the DOM after each refresh.

Any one able to help me out?

Thanks

2
  • Your cookie value only contains none !important, you need to add display: Commented Jul 7, 2013 at 10:39
  • Please use JS FIDDLE. Commented Jul 7, 2013 at 10:39

2 Answers 2

3

Should not use attr('style') as it will override all your styles. Use .css instead. An also try avoiding !important. Try

$('#cartHolder').css('display','none');
$.cookie("cartDisplay", 'none');

In your header.

$(document).ready(function(){
    if ($.cookie("cartDisplay")){
           $('#cartHolder').css('display', $.cookie("cartDisplay"));
       }
});

Or you could use .toggle

$('#cartHolder').hide();
$.cookie("cartDisplay", 'false');

In your header.

$(document).ready(function(){
    if ($.cookie("cartDisplay")){
           $('#cartHolder').toggle($.cookie("cartDisplay"));
       }
});

Remember to wrap the code inside $(document).ready(function(){ to ensure the DOM elements have been loaded

Sign up to request clarification or add additional context in comments.

3 Comments

correct but its duplicate I think and could be a comment under an answer.
OK nice +1 to your description. please check mine too.
@KhanhTO yep that's it, sorry for this elementary mistake. Forgot to include document.ready :D cheers
3

The String You get back from your cookie is this:

none !important

and the thing you give to your element is this:

 <div style="none !important"></div>

make it complete in your coockie, like:

display:none !important

EDIT
its better to use it like this:

 $('#cartHolder').css('display', $.cookie("cartDisplay"))

and there is no need to change the cookie code of yours.(it should work)

2 Comments

I've tried your suggestion and it still returns undefined in the final CSS in the DOM
sorry i didnot get it do you need description? and plus thanks for your +1

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.