javascriptsidenav

Keeping Side Nav Open to current url Javascript


I've been trying to keep my mySidenav open when a user selects the in mySidenav() which re-directs to a new page. Once the new page loads I have a seperate js file that has a ready(function)

$(document).ready(function(){
document.getElementById("myMainNav").classList.add('sideNavOpen');
document.getElementById("main").classList.add('lmarg250');
document.getElementById("mySidenav"+num).classList.add('sideNavOpen');
document.getElementById("main").classList.add('lmarg500');
let span = document.getElementById("open");
    if (span.innerHTML === String.fromCharCode(9776).concat(" Open") )
      span.innerText = String.fromCharCode(9776);
    else
      span.innerText = String.fromCharCode(9776).concat(" Open");


});

The above code keeps myMainNav open but Doesn't keep mySidenav open. I'm assuming due to it not knowing what value +num is as the html link for the page doesn't specify it:

<div id="mySidenav2" class="sub-sidenav">
        <a onclick="closeSubNavs()" href="javascript:void(0)" class="closebtn2">&times;</a>
        <a href="soup.html">Soup</a>
        <a href="garlicbread.html">Garlic Bread</a>
        <a href="frenchfries.html">French Fries</a>
        <a href="loaded.html">Loaded Fries</a>
        <a href="ques.html">Quesadilla</a>
        <a href="nachos.html">Nachos</a>
        <a href="pbagel.html">Pizza Bagel</a>
      </div>

Is there a way to specify the page or maybe "current address / url?" and would this fix the problem or perhaps give the tag an id of id="mySidenav2" etc.


Solution

  • You can use window.location.pathname to extract the current page and logically decide if the sidebar should be opened according to that.

    something like:

    if(window.location.path === "/garlicbread.html"){
      document.getElementById("mySidenav"+2).classList.add('sideNavOpen');
    
    }
    

    An easier method though could be just storing the num value in the localStorage object and retrieving it from there.

    // at load:
    let num = window.localStorage.getItem('num');
    
    // When saving:
    window.localStorage.setItem('num', num);
    

    docs: - window.location - window.localStorage