How to save a submenu when changing a page

I have this JS code for my menu:

$(document).ready(function () { $('#nav > li > a').click(function(e){ if ($(this).attr('class') != 'active'){ $('#nav li ul').slideUp(); $(this).next().slideToggle(); $('#nav li a').removeClass('active'); $(this).addClass('active'); } }); }); 

What is the best way to make a submenu open when a page changes - possibly with cookies or sessions?

Here I created jsfiddle so you can see the full html and css, etc .: http://jsfiddle.net/bMkEj/

+4
source share
3 answers

This can be done using HTML5 LocalStorage .

In the click handler, save the text of the active menu to localStorage:

 $('#nav > li > a').click(function(e){ ... localStorage.setItem("activeSubMenu", $(this).text()); }); 

Download the page, read localStorage and expand the menu (if found):

 $(document).ready(function(){ var activeItem = localStorage.getItem("activeSubMenu"); if(activeItem){ $('#nav > li > a').filter(function() { return $(this).text() == activeItem; }).slideToggle(); } }); 
+2
source

Pass the query parameter when the page loads and use it to select the appropriate navigation item:

HTML

 <ul> <li id="foo"><a href="index.html?nav=foo">Foo</a> <ul> <li>Foo 1</li> <li>Foo 2</li> </ul> </li> <li id="bar"><a href="index.html?nav=bar">Bar</a> <ul> <li>Bar 1</li> <li>Bar 2</li> </ul> </li> <li id="baz"><a href="index.html?nav=baz">Baz</a> <ul> <li>Baz 1</li> <li>Baz 2</li> </ul> </li> </ul> 

JS (accepts jQuery)

 $(document).ready(function() { var query = decodeURIComponent(window.location.search); var matches = query.match(/nav=([^&]*)/); var id = matches[1]; $('#' + id + ' ul').slideDown(); }); 
+1
source

If you use PHP or any other server language, you can add the active class to the active element.

EDIT: if you just run JS, you can parse the url (window.location.href) and use it to set the active class.

0
source

Source: https://habr.com/ru/post/1487043/


All Articles