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 .

Obmerk Kronen
  • 15,619
  • 16
  • 66
  • 105

2 Answers2

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.

ggdx
  • 3,024
  • 4
  • 32
  • 48
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);
        }

    },
SSA
  • 5,433
  • 4
  • 36
  • 50
  • 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. – Obmerk Kronen Sep 22 '14 at 15:43
  • 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 http://www.w3schools.com/js/tryit.asp?filename=tryjs_oper_incr and then change ++yy to y++ and check again. This will explain. – SSA Sep 22 '14 at 16:22
  • Ok, So, I guess you are talking performance wise regarding the cookie. regarding the preincrement, I got the tip and examples [from here](http://stackoverflow.com/a/1547280/1244126) after reading your first comment. Thanks again .. – Obmerk Kronen Sep 22 '14 at 22:59