Search code examples
jquerycookiesjquery-cookie

Check cookie and addClass, but it is to slow


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');
    }
});

Solution

  • 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.