Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Don't know how to put the question title correctly! I have a div that is displayed by button click. The problem is that if user goes to next page(by clicking another button) and then come back to the old page the div is not shown because page is refreshed, so user needs to click the button again to see the div.

Is there any way to keep div displayed after button clicked for first time?

<div id="tableDiv" style="display:none;" >
<table>
   <td>something</td>
</table>
</div>

<input type="button" value="Show" onClick="showTable()"/>

<script type="text/javascript">         
   function showTable() {
       document.getElementById('tableDiv').style.display = "block";
   }                
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
582 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the html5 webStorage for this:

localStorage does not expire, whereas sessionStorage gets deleted when the browser is closed (usage of both is equivalent). The webStorage is support by all major browsers and IE >= 8

Plain Javascript

function showTable() {
   document.getElementById('tableDiv').style.display = "block";
   localStorage.setItem('show', 'true'); //store state in localStorage
}

And check the state onLoad:

window.onload = function() {
    var show = localStorage.getItem('show');
    if(show === 'true'){
         document.getElementById('tableDiv').style.display = "block";
    }
}

jQuery

function showTable() {
    $('#tableDiv').show();
    localStorage.setItem('show', 'true'); //store state in localStorage
}

$(document).ready(function(){
    var show = localStorage.getItem('show');
    if(show === 'true'){
        $('#tableDiv').show();
    }
});

Demo

P.S. To remove an item from the localStorage use

localStorage.removeItem('show');

Reference

webStorage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...