Reputation: 2415
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
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();
}
};
Upvotes: 5
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
Reputation: 5428
try this one:
window.onload = function() {document.getElementById('message-box').style.display="block";};
Upvotes: 0