I have a local html file that I use for note taking, which I divide into hidden sections that I can access individually by clicking on their buttons at the top of the page. The problem is that when I reload the page after updating its content, it reverts to its default state of not having any sections open and I lose my place. I need a way for the page to preserve its state but still update content upon reloading (preferably not using another button, since scrolling back up to the top to press it defeats the purpose).
Unfortunately, JavaScript is not my area of expertise and the few online guides I have found for goals similar to what I’m trying to accomplish did not explain things well.
Here’s the relevant code I have so far. It meets my needs for automatically hiding the sections I’m not currently using, but doesn’t remember which one is open when I reload the page after updating the sections’ contents.
HTML
/* Navigation menu */
<button onclick="openPage('1')">First Section</button>
<button onclick="openPage('2')">Second Section</button>
<button onclick="openPage('None')">Hide All Sections</button>
/* Sections of my notes */
<section id="1" class="tabcontent">
</section>
<section id="2" class="tabcontent">
</section>
CSS
.tabcontent {
display: none; // Hides all sections by default
}
JavaScript
function openPage(pageName, elmnt) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none"; // Hide all other sections
}
document.getElementById(pageName).style.display = "block"; // Shows the section I specified
}
2
Answers
To do what you require you need to store the state of the page somewhere between page loads. LocalStorage would be the ideal place for this. Here’s an example of how this can be implemented.
Note that it sets a local storage key when a button is clicked, remove that key when the clear button is clicked, and also reads from local storage when the page first loads in order to show the last displayed content.
Here’s a working example in a jsFiddle, as SO snippets are sandboxed and deny access to local storage.
you should use localstorage in javascript for your purspose
css code:
html Code
java Script code