admin管理员组文章数量:1419238
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";};
本文标签: javascriptshow the div even after the page reloadStack Overflow
版权声明:本文标题:javascript - show the div even after the page reload - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745299877a2652307.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论