Jquery – Stop div from showing more than once per session or visit

jquery

I have a JS function that shows a message div on doc ready and then hides it if the 'close' link is clicked.

I would like to show this message div only once per visit to the first page the user visits and then then never for any page view in the site after that.

At the moment when a user clicks on another page within the site, the message div shows again and this is annoying obviously for everyone.

I looked up 'one' in jQuery but am not sure how to implement it with my low JS knowledge.

<script>
$(document).ready(function(){
    $("div#panel").hide();

    var autoTimer = null;

    autoTimer = setTimeout(function(){
        $("div#panel").slideDown("slow");
    },1000);
    $("#close").click(function(){
        $("div#panel").slideUp("slow"); 
        if(autoTimer) clearTimeout(autoTimer);
        autoTimer = null;
        $("div#close").css("display","none");
    });         
});
</script>

Best Answer

Create a localStorage key, set it when the user gets to the page, and remove it when the user leaves the page:

//On user coming to page:
//Check localStorage on each page visit, if it's null, show your div
if (!localStorage.getItem("visited")) {
    //show the div

    //Set the key
    localStorage.setItem("visited", "true");
}

//clear localStorage on tab close
window.onbeforeunload = function() {
    localStorage.removeItem("visited");
};
Related Topic