1

Using the jquery cookie plugin I have a very simple function as so :

demoPopupInit: function() { // alert($.cookie('modal-popup')); if (! $.cookie('modal-popup')) { $.cookie('modal-popup',1) ; } if ( $.cookie('modal-popup') <= 3 ) { // return; var modal_cookie = $.cookie('modal-popup') ; modal_cookie = modal_cookie++; $("#intro_index").modal({backdrop:true}); $.cookie('modal-popup', modal_cookie ); } }, } 

I am sure it is a very simple mistake, but my poor JS skills do not allow me to understand why the alert() in the begining always turn 1..

I also tried

 if (! $.cookie('modal-popup') == NULL) { $.cookie('modal-popup',1) ; 

But of course ,the problem is not there , and no other error reported in console. My aim is to turn the modal pop-up on only on 3 first visits .

2 Answers 2

1

Just change post increment to preincrement:

modal_cookie = modal_cookie++; 

to

modal_cookie = ++modal_cookie; 

Also cookie returns a string value, to be safe use parseInt to compare int value. and avoid reading cookie multiple times, save it in a varible.

Short:

demoPopupInit: function() { if (!$.cookie('modal-popup')) { $.cookie('modal-popup',1) ; } var curval = parseInt($.cookie('modal-popup')); if ( curval <= 3 ) { // return; $("#intro_index").modal({backdrop:true}); $.cookie('modal-popup', ++curval); } }, 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this indeed works . I infact tried to use parseInt() before - I do not know why it still did not work. Can you maybe explain to me why reading a cookie multime times is not a good practice ? ( I also do not understand why ++modal_cookie matters , but maybe it is for another question . Very helpful.
You are using a plugin, which may internally runs a loop or may be regex to find the value out of cookie collection based on name passed, has clear overhead, so calling it multiple times is unnecessary and costly when you can do by reading it once. For you second question, try this w3schools.com/js/tryit.asp?filename=tryjs_oper_incr and then change ++yy to y++ and check again. This will explain.
Ok, So, I guess you are talking performance wise regarding the cookie. regarding the preincrement, I got the tip and examples from here after reading your first comment. Thanks again ..
1

Try:

if($.cookie('modal-popup').length < 1){ $.cookie('modal-popup',1); } 

If the cookie doesn't exist, the length will be -1; if it does, it will be 1 or greater.

3 Comments

Yep.. it is counting now, but not stopping at 3 ( ? ? )
Is 3 meant to be the cookie value or number of cookies?
3 is a value of the cookie ( times for popup to appear )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.