showing results for - "if path name is different but parent nav should be active in jquery"
Camilo
15 Jun 2016
1$(document).ready(function() {
2
3 // Get current page URL
4 var url = window.location.href;
5
6 // remove # from URL
7 url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
8
9 // remove parameters from URL
10 url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
11
12 // select file name
13 url = url.substr(url.lastIndexOf("/") + 1);
14 
15 // If file name not avilable
16 if(url == ''){
17 url = 'index.html';
18 }
19 
20 // Loop all menu items
21 $('.menu li').each(function(){
22
23  // select href
24  var href = $(this).find('a').attr('href');
25
26  // Check filename
27  if(url == href){
28
29   // Select parent class
30   var parentClass = $(this).parent('ul').attr('class');
31 
32   if(parentClass == 'submenu'){
33 
34    // Add class
35    $(this).addClass('subactive');
36    $(this).parents('.menu li').addClass('active');
37   }else{
38
39    // Add class
40    $(this).addClass('active');
41   }
42 
43  }
44 });
45});
Avery
01 Aug 2020
1<ul class='menu'>
2 <li><a href="index.html">Home</a></li>
3 <li><a href="javascript.html">JavaScript</a>
4  <ul class='submenu'>
5   <li><a href="angular.html">AngularJS</a></li>
6   <li><a href="jquery.html">jQuery</a></li>
7   <li><a href="react.html">React JS</a></li>
8  </ul>
9 </li>
10 <li><a href="blog.html">Blog</a></li>
11</ul>