StealthTrails
StealthTrails

Reputation: 2415

show the div even after the page reload

On click of a button, I am showing a div by using

document.getElementById('message-box').style.display="block";

but when the page is reloaded this div disappears again. I want the div to stay until i explicitly close it with x button. How I can do this?

Upvotes: 0

Views: 3323

Answers (3)

Ziv Weissman
Ziv Weissman

Reputation: 4536

This simple example will do what you want to achieve

html:

<div class='hidden' id='hiddenDiv'>NOT SHOWN UNTIL YOU CLICK IT!! <span>
        <input type='button' value='X' onclick='closeClick()'>
    </span>

</div>
<input type='button' value='show me the div' onclick='openClick()' />

JS:

function openClick() {
    document.getElementById('hiddenDiv').style.display = "block";
    sessionStorage.setItem('clicked', true);
}

function closeClick() {
    document.getElementById('hiddenDiv').style.display = "none";
    sessionStorage.removeItem('clicked');
}

window.onload = function () {
    var data = sessionStorage.getItem('clicked');
    if (data == 'true') {
        openClick();
    }
};

fiddle example

Upvotes: 5

sadiqevani
sadiqevani

Reputation: 500

I am not going to write code on here, since it makes a developer lazy by copy/pasting, but i am going to tell you how you can solve it.

The issue in here is that, you refresh the page, and the state of that div is removed, since is not a persistent state.

A solution for this, is either cookies, or localStorage, where you can set off a variable, if the button is off or not.

Hope this helps.

Upvotes: 2

Vassily
Vassily

Reputation: 5428

try this one:

window.onload = function() {document.getElementById('message-box').style.display="block";};

Upvotes: 0

Related Questions