Answers for "if path name is different but parent nav should be active in jquery"

0

if path name is different but parent nav should be active in jquery

<ul class='menu'>
 <li><a href="index.html">Home</a></li>
 <li><a href="javascript.html">JavaScript</a>
  <ul class='submenu'>
   <li><a href="angular.html">AngularJS</a></li>
   <li><a href="jquery.html">jQuery</a></li>
   <li><a href="react.html">React JS</a></li>
  </ul>
 </li>
 <li><a href="blog.html">Blog</a></li>
</ul>
Posted by: Guest on June-17-2021
0

if path name is different but parent nav should be active in jquery

$(document).ready(function() {

 // Get current page URL
 var url = window.location.href;

 // remove # from URL
 url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));

 // remove parameters from URL
 url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));

 // select file name
 url = url.substr(url.lastIndexOf("/") + 1);
 
 // If file name not avilable
 if(url == ''){
 url = 'index.html';
 }
 
 // Loop all menu items
 $('.menu li').each(function(){

  // select href
  var href = $(this).find('a').attr('href');

  // Check filename
  if(url == href){

   // Select parent class
   var parentClass = $(this).parent('ul').attr('class');
 
   if(parentClass == 'submenu'){
 
    // Add class
    $(this).addClass('subactive');
    $(this).parents('.menu li').addClass('active');
   }else{

    // Add class
    $(this).addClass('active');
   }
 
  }
 });
});
Posted by: Guest on June-17-2021

Code answers related to "if path name is different but parent nav should be active in jquery"

Code answers related to "Javascript"

Browse Popular Code Answers by Language