1

I am trying to create a jQuery based style switcher which changes the body class depending on the number of visits ot the website.

The problem I am having is that the code I am using changes the class on every page load rather than per visit. The number of visits also alerts a NaN value in Safari.

Do I need to specify a session time? How can this be achieved? I am using the jquery.cookie plugin, here is the code:

if(!$.cookie('visits')){
     $.cookie('visits',1, {expires: 30});
   }
   $.cookie('visits', (parseInt($.cookie('visits')) + 1), {expires: 30}) 
       //will expire after 30 days

       if(parseInt($.cookie('visits')) == 2){
        $('body').removeClass().addClass('blue');  
       } else if (parseInt($.cookie('visits')) == 3){
        $('body').removeClass().addClass('green');  
       } else if (parseInt($.cookie('visits')) == 4){
        $('body').removeClass().addClass('purple');  
       } else if (parseInt($.cookie('visits')) == 5){
        $('body').removeClass().addClass('red');  
       } else if (parseInt($.cookie('visits')) > 5){
        $.cookie('visits', 1);               
   };

Help appreciated :)

1 Answer 1

1
if(!$.cookie('visits')){
     $.cookie('visits',0, {expires: 30});
   }
if(!$.cookie('last') or parseInt($.cookie('last'))+600000<new Date().getTime()) // 10minutes expired, new visit

$.cookie('visits', (parseInt($.cookie('visits')) + 1), {expires: 30}) 
   //will expire after 30 days
   $.cookie('last',new Date().getTime(),{expires: 1});
   if(parseInt($.cookie('visits')) == 2){
    $('body').removeClass().addClass('blue');  
   } else if (parseInt($.cookie('visits')) == 3){
    $('body').removeClass().addClass('green');  
   } else if (parseInt($.cookie('visits')) == 4){
    $('body').removeClass().addClass('purple');  
   } else if (parseInt($.cookie('visits')) == 5){
    $('body').removeClass().addClass('red');  
   } else if (parseInt($.cookie('visits')) > 5){
    $.cookie('visits', 1);               
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick answer, unfortunately it still seems to change on every page load.
Did you tried edited post? (with 600000). It works on my local site

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.