I have a left side vertical nav menu with a couple sections that collapse submenus. How can I make it so that when the user navigates to a page from that submenu (#submenu1) that the menu is expanded on the next page?
<ul >
<li >
<a href="#submenu1" data-toggle="collapse" data-target="#submenu1">
<i ></i><span >Your Account</span>
</a>
<div id="submenu1" aria-expanded="false">
<ul >
CodePudding user response:
Here you go...
You'll need to use a little bit of JavaScript/jQuery.
STEP 1
Add query string when user clicks on a link (source).
element.addEventListener('click', function(event) {
// Stop the link from redirecting
event.preventDefault();
// Redirect instead with JavaScript
window.location.href = element.href '?menu=uncollapsed';
}, false);
STEP 2
Check query string value on a page load (source).
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "menu" --> "https://example.com/?menu=uncollapsed"
let value = params.menu; // "uncollapsed"
STEP 3
If the value of "menu" is "uncollapsed" on a page load, then remove collapsed
and add show
Bootstrap classes.
$( document ).ready(function() {
$('.navbar-toggler').removeClass('collapsed');
$('.navbar-collapse').addClass('show');
});
Note: These three steps will not work if you just copy-paste the code from my answer. You need to add a few minor things (e.g., if statement in the STEP 3), but this is the way I think you could make it work.