Search code examples
jquerycookiesonload-event

Jquery cookies not working: Trigger on inital load ONLY


I want to have a container div fade in on initial load ONLY, and when I click on link div, it links back to the homepage but without triggering the fade. I've been trying to use cookies but I'm not familiar with it and it doesn't seem to work (the fadein always triggers not matter what). Can anyone help?

http://codepen.io/alga/full/vKEuL

JQUERY:

if ($.cookie('cookie_set')) {
$('#container').css('opacity', 1);
} else {
  $.cookie('cookie_set');
$("#container").delay(1000).animate({
    opacity: 1

}, 2000);
}

CSS:

#container {background:blue;opacity:0;width:100px;height:100px;}

HTML:

<div id="container"></div>

<div id="link"><a href="http://codepen.io/alga/full/vKEuL">back</a></div>

Solution

  • You need to set a value to the cookie by passing a second argument to the $.cookie() call, else the value of the cookie will not get set

    if ($.cookie('cookie_set')) {
        $('#container').css('opacity', 1);
    } else {
        $.cookie('cookie_set', '1');
        $("#container").delay(1000).animate({
            opacity: 1
    
        }, 2000);
    }
    

    Demo: Fiddle

    If you pass only a single argument then in will be considered as a getter request, then if the cookie is already exists that value will be returned else undefined will be returned - the value will not get set in this case.

    You need to set the cookie some value so that during the second execution you can find the cookie.