Dirty Bird Design Dirty Bird Design - 2 months ago 8
jQuery Question

local storage - show modal once on wp page

I dont know if this is a wp centered issue, but Ive done this before and can't get it to work in a WordPress environment. Basically, I want to show a modal dialog box on the first visit to the site, and not on following visits in same session.

function slideIn() {
jQuery('#overlay').fadeIn('fast');
}

function slideOut () {
jQuery('#overlay').fadeOut('fast');
}
jQuery(function() {
//local storage lasts until cache cleared
if(sessionStorage.getItem('slideState') != 'shown'){
slideIn();
sessionStorage.setItem('slideState','shown');
}
jQuery(document).on('click', '#popInClose', function(e){
slideOut();
e.preventDefault();
sessionStorage.setItem('slideState','shown');
});
});


When I load page for first time, modal displays as expected. When I close it and either reload the page or go to another page, it is displaying again, which is not desired.

Answer

You just need to set some defaults and work from them. Something like this will work.

    var state = (sessionStorage.getItem('seen') == 'seen') ? 'seen' : 'unseen'; 
    if (state == 'seen') { 
        slideOut(); //Or whatever to hide the modal
    }
    else { 
        slideIn(); //Or whatever to show the modal
        sessionStorage.setItem('seen','seen'); //Set state as seen
    }