0

I want to use a simple client side jquery cookie to limit the viewing of an element. Pretty straight forward, and it have been asked in variation here before, I know.

I would also like to reference the localStorage and sessionStorage plugin I am using: by Yannick Albert

So where I am at is this as far as jQuery is concerned, these are the first lines in my $(document).ready(function(){

$(function (){
    if( $.cookie('sessionCookie') == "sessionVisit" ){
        $('#element').hide();
    }
    else if( $.localStorage('sessionCookie') == "sessionVisit" ){
        $('#element').hide();
    }
    else{
        return false;
    }
});

$(function(){
    var chromeBrowser = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    (chromeBrowser)?$.localStorage('sessionCookie', 'sessionVisit'):$.cookie('sessionCookie', 'sessionVisit');
});

It works completely OK in Firefox. I load the page once or for the first time, and the element is there. When I reload, it is not there.

Safari and Chrome though, it feels as though the $.localStorage does not wait for a re-load. the element never shows. I don't know the technical term for it but the $.localStorage is read straight away, even though I believe that I did the sequence correct and the $.localStorage is made after the 'check'.

If that makes any sense. So what logic or syntax errors am I making?

I used this question as my jumping point.

Community
  • 1
  • 1
brian-welch
  • 441
  • 1
  • 7
  • 19

1 Answers1

0

I don't know if this is the right answer, but it is working with these changes:

$(function (){
    if( $.cookie('sessionCookie') == "sessionVisit" ){
        $('#element').hide();
    }
    else if( $.sessionStorage('chromeCookie') == "chromeVisit" ){
        $('#element').hide();
    }
    else{
        return false;
    }
});
$(function(){
    var chromeBrowser = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    (chromeBrowser)?
        $.sessionStorage('chromeCookie', 'chromeVisit'):
            $.cookie('sessionCookie', 'sessionVisit');
});

The first bug I had was that I was using identical strings for the localStorage and the cookie key and value. This must have caused a significant error there.

Then, I found that the localStorage was not removed when the browser was closed. So after the localStorage value was placed, it appears to remain there until it is over written, which has it's value certainly, but not what I needed. So the plugin's sessionStorage was perfectly suited to the task.

All is working as needed and expected. I have yet to test on IE, so not sure how it will perform there.

brian-welch
  • 441
  • 1
  • 7
  • 19