0

On window load function I check if there is a cookie and I add a css class to hide an element. But it is not fast enough, when open the site it shows the hidden element for a second. Any better way to do that without seeing the hidden element?

This is the script I am using (I use jQuery):

$(window).load(function() {
    if ($.cookie('note')) {
        $('.note').addClass('hide');
    }
});
Liam
  • 27,717
  • 28
  • 128
  • 190

1 Answers1

2

Simply invert the function to only show the image if the cookie doesn't exist:

$(window).ready(function() {
    if (typeof $.cookie('note') === 'undefined') {
        $('.note').removeClass('hide');
    }
});

Obviously your default state should include the hide class.

also, as mentioned don't use load() it's deprecated, doesn't work very well and add's an unnecessary delay to your code running.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • I am trying this, but this does not work: if (typeof $.cookie('note') === 'undefined' – Oliver Schmid Mar 28 '16 at 10:36
  • What happens [when you debug it?](http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) – Liam Mar 29 '16 at 07:44
  • I get this: 116 Uncaught TypeError: $.cookie is not a function https://drive.google.com/file/d/0B4_0PpHmsIheWU5JZkRGT3RWNkE/view?usp=sharing – Oliver Schmid Mar 29 '16 at 09:07
  • But you were using $.cookie above o_O. This is a different question, [answered here](http://stackoverflow.com/questions/4034190/cookie-is-not-a-function) – Liam Mar 29 '16 at 09:56
  • Ok thanks! Is there a way doing it without the jQuery Cookie plugin? – Oliver Schmid Mar 29 '16 at 10:02
  • Mmhh if I add the jQuery Cookie Plugin the error goes away, but the class hide won't be removed. – Oliver Schmid Mar 29 '16 at 10:38