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?
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?
- 3 Set and check cookie. developer.mozilla/en-US/docs/Web/API/Document/cookie – sinisake Commented Aug 29, 2015 at 20:18
- any example? never mind, I am just a newbie in js – StealthTrails Commented Aug 29, 2015 at 20:21
- As @nevermind said you need to have a variable in cookie or localStorage. Set the cookie or variable to true when the button to show div is clicked. And set to false once the x is clicked. Combine that with Vassiliy's answer at bottom to show div after reload if the value of cookie or variable is true. You can find many tutorials and examples on handling cookies and localStorage. – Jehanzeb.Malik Commented Aug 29, 2015 at 20:25
3 Answers
Reset to default 5This 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
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.
try this one:
window.onload = function() {document.getElementById('message-box').style.display="block";};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745299878a4621371.html
评论列表(0条)