Rakib Roni Rakib Roni - 7 months ago 21
Javascript Question

Multiple lavel dropdown menu set active using jQuery

When I click a menu example "C" then I want to set class active. It also should be active after reload of the page.

<ul class="nav metismenu" id="side-menu">
<li>
<a href="#">Dashboards</a>
<ul class="nav nav-second-level collapse">
<li><a href="#A">A</a></li>
<li><a href="#B">B</a></li>
<li><a href="#C">C</a></li>
<li><a href="#D">D</a></li>
<li><a href="#E">E</a></li>
</ul>
</li>
<li>
<a href="F">F</a>
</li>
</ul>


To set a class active the code is :

<ul class="nav metismenu" id="side-menu">
<li class="active">
<a href="#">Dashboards</a>
<ul class="nav nav-second-level collapse">
<li><a href="#A">A</a></li>
<li><a href="#B">B</a></li>
<li class="active"><a href="#C">C</a></li>
<li><a href="#D">D</a></li>
<li><a href="#E">E</a></li>
</ul>
</li>
<li>
<a href="F">F</a>
</li>
</ul>

Answer

First, I invite you to learn more about cookies .

So , for this case Here is Working Fiddle => jsFiddle i used JQuery in the fiddle (dont forget to use Jquery in your sources)

ps: for security issues Snippet can't work here !!

JS :

$( document ).ready(function(){
  if(typeof(getCookie("activeLi")) != "undefined" && getCookie("activeLi").length>0){
    $('#side-menu ul a[ href=' + getCookie("activeLi") + ']').parent().addClass("active");
  }
  $("#side-menu ul a").click(function(a){
        if(typeof(getCookie("activeLi")) != "undefined");
        alert(getCookie("activeLi"));
        removeActive();
        $(this).parent().addClass("active");
      setActiveCookie(this.getAttribute("href"));
  });
});

function removeActive(){
    $("#side-menu ul li").each(function(li){
    $(this).removeClass("active");
  })
}

function setActiveCookie(active){
      //document.cookie="activeLi="+active;
    var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000)); // expire in 30 days
    var expires = "expires="+d.toUTCString();
    document.cookie="activeLi="+active+"; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

CSS :

.active a {
  color: green;
}
a {
  text-decoration: none;
}

HTML :

<ul class="nav metismenu" id="side-menu">                 
<li>
    <a href="#">Dashboards</a>
    <ul class="nav nav-second-level collapse">
        <li><a href="#A">A</a></li>
        <li><a href="#B">B</a></li>
        <li><a href="#C">C</a></li>
        <li><a href="#D">D</a></li>
        <li><a href="#E">E</a></li>
    </ul>
</li>
<li>
    <a href="F">F</a>
</li>