Use html session storage to hide a div after it's run once

2.1k views Asked by At

I have this div with an id of se-pre-con in my website which I only want to display once per website visit. I want to use session storage to display none the html div of se-pre-con after it's run once. But could do with some advice about how to approach this.

 <div class="se-pre-con"></div> // the relevant html

.no-js #loader { display: none;  } // the relevant css
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(Preloader_10.gif) center no-repeat #fff;
}

 <script> // the relevant jquery

// Wait for window load
$(window).load(function() {
    // Animate loader off screen
    $(".se-pre-con").fadeOut("slow");;
});


</script>
2

There are 2 answers

0
AudioBubble On BEST ANSWER

I answered my own question by using this script in the body section of the html page, it ensures the loader only ever runs once per browser session, exactly as I was trying to achieve.

<script>
if (sessionStorage.getItem('se-pre-con') !== 'true'){
// if the storage item 'se-pre-con', does not exist, run the code in curly 
braces
document.getElementById("se-pre-con").style.display = 'block';}

else {
document.getElementById('se-pre-con').style.display="none";
// else (when above if statement is not met) hide the loader
}


sessionStorage.setItem('se-pre-con','true');

</script>
0
Federico klez Culloca On

It's still not clear where you want to call that code from, but if I were you, I would reverse the code a bit. That is, always execute your stuff on the load event and decide what to do while in there. At that point it becomes trivial to put the loading of the object you want to fade out inside a function and call that piece of code from somewhere else (and you don't specify where you want to call it from, so I'll have to guess you want to call it after you set the value inside your sessionStorage.

function fadeObject() {
    $(".se-pre-con").fadeOut("slow");
}

$(window).load(function() {
    if (sessionStorage.getItem('htmldivwithid') !== 'false') {
        fadeObject();
    } else {
        document.getElementById('htmldivwithid').style.display="none";
        sessionStorage.setItem('htmldivwithid','true');
        // call fadeObject()?
    }
});

At this point you can call fadeObject() when you need it, from inside the load event (I put a comment where I expect you might want to call it).

fadeObject is not strictly necessary, but in case you need to change the object that fades you now have just one place to change instead of two, once you decide where you want to call it.