Home >Web Front-end >CSS Tutorial >How to Preserve Menu State on Page Reload using Modern Browsers?
Problem Statement:
You have a menu with multiple links, where:
Solution: Leveraging localStorage
To achieve the desired menu behavior, we can utilize HTML5 localStorage to store and retrieve the state of the selected link. Here's a step-by-step guide:
<code class="js">const selectedLinkId = localStorage.getItem('selectedLinkId');</code>
<code class="js">if (selectedLinkId) { $(`#${selectedLinkId}`).addClass('hovered').siblings().removeClass('hovered'); }</code>
<code class="js">$('#menuLinks').on('click', function() { localStorage.setItem('selectedLinkId', $(this).attr('id')); });</code>
<code class="js">window.addEventListener('pageshow', function() { localStorage.removeItem('selectedLinkId'); });</code>
Pros and Cons of Storage Location:
localStorage:
Server-side:
Ultimately, the best storage location depends on your specific requirements. localStorage is a suitable option for persistent user settings that do not require significant amounts of storage.
The above is the detailed content of How to Preserve Menu State on Page Reload using Modern Browsers?. For more information, please follow other related articles on the PHP Chinese website!