ian305
ian305

Reputation: 25

Keep a <div> displayed after page reload

The problem is simple, I just can't find a way to solve it. I just to display a text with a click of a button but when the page is reloaded I want the text to still be displayed without clicking the button again. My code is the following:

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous">
</script>
<div id='result' style: 'display:none;'>
  <p></p>
</div>
<form method="post" action="#">
    <input type="button" value="Show" id='button'/>
</form>

<script type="text/javascript">
$(document).ready(function(){
    var div1Show = localStorage.getItem('div1_show');
    if (div1Show) {
        $("#div1").remove();
    } else {
        $("#div1").show();
    }
    $("#button").click(function(){
        $("#result").text("Complete");
        $("#div1").show();
        localStorage.setItem('div1_show', 'true');
    });
});
</script>

Upvotes: 0

Views: 43

Answers (1)

David Teather
David Teather

Reputation: 598

You are placing a string into the cookie just change the following line

localStorage.setItem('div1_show', 'true');

To a boolean

localStorage.setItem('div1_show', true);

Upvotes: 1

Related Questions