开发者

Crumbling Cookies with jQuery

Here is what i want to do - run a series of jQuery animations the first time someone visits my website.

I want to do this using standard jQuery calls for the animation and the jQuery Cookie plugin to log whether they have visited before.

Most of what i want is working with this code:

<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery.cookie('visited', 'no', { expires: 14 });
    var visited = jQuery.cookie('visited');
    if (visited == 'no') {
         jQuery("#navigation-wrap").delay(500).animate({ 
      marginLeft: "0px"
      }, 500 );
   jQuery('.page-navigation').delay(1000).slideToggle(400);
   jQuery('.page-navigation').delay(1000).slideUp(300);
   jQuery("#navigation-wrap").delay(2000).animate({ 
      marginLeft: "-180px"
      }, 500 );     
       }
     jQuery.cookie('visited', 'yes');
 });
</script>

But, even though the Cookie value is being changed to 'yes' after a visit,开发者_开发问答 the animations still run if I refresh the page...


You are setting the cookie back to 'no' every time the page reloads with this line:

jQuery.cookie('visited', 'no', { expires: 14 });

Then when your if statement checks if the value is 'no' it returns true because you literally changed it to 'no' 2 lines above.

You will have to check for the existence of the cookie first and then place it.

Example

As soon as jQuery fires the ready event of the document you execute the following piece of code:

jQuery.cookie('visited', 'no', { expires: 14 });

This sets the visited cookie to the value 'no'. After you've set the cookie you retrieve it and check if the value is equal to 'no', which it now is.

var visited = jQuery.cookie('visited');
if (visited == 'no') {
    ...
}

And after the if statement you set the visited cookie's value to 'yes'. But as soon as you reload the page we're back at step one again because the visited cookie's value is set back to the value 'no'.


Thanks to Kevin for pointing this out and to @Johnnyb on CSS-tricks.com

This code does as required:

    <script type="text/javascript">
    jQuery(document).ready(function() {
        var visited = jQuery.cookie('visited');
        if (visited == 'yes') {
            return false;
        } else {
             jQuery("#navigation-wrap").delay(500).animate({ 
          marginLeft: "0px"
          }, 500 );
       jQuery('.page-navigation').delay(1000).slideToggle(400);
       jQuery('.page-navigation').delay(1000).slideUp(300);
       jQuery("#navigation-wrap").delay(2000).animate({ 
          marginLeft: "-180px"
          }, 500 );     
           }
         jQuery.cookie('visited', 'yes', { expires: 7 });
     });
 </script>

Thanks for your help, guys!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜