You could check if the href attribute is in the current URL with this function.
$(".dropdown-menu a").each(function() {
let href = $(this).attr('href');
if (window.location.href.indexOf(href)) {
$(this).parent('li').addClass('active');
}
});
Please note that ‘/’ will always be true.
I think this should be a dynamic one. Right? Because routes are different. So to catch the route url we need to use dynamic value in this case window.location.href
. This snippet will resolve the problem –
JavaScript
$(document).ready(function() {
var url = window.location.href
var parts = url.split("/")
var route = parts[parts.length-1]
console.log(route)
if(route){
$('a[href*="/'+route+'"]').parent('li').addClass('active');
}
});
CSS
.active { background: red !important } /* for example */
You can do something below.
var url = "http://localhost/app/home",
parts = url.split("/"),
last = parts[parts.length-1];
if(last){
$('a[href*="/'+last+'"]').parents('li').addClass('active');
}
.dropdown-menu .active{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="dropdown active">
<a href="#" class="nav-link has-dropdown" data-toggle="dropdown"><i class="fas fa-list"></i> <span>Outlook</span></a>
<ul class="dropdown-menu" style="display: block;">
<li class=""><a class="nav-link" href="/home"><span>Sales</span></a></li>
<li><a class="nav-link" href="/"><span>Product</span></a></li>
<li><a class="nav-link" href="/"><span>Channel</span></a></li>
</ul>
</li>
Thanks for the answers… this is my full code how to solve this
var url = window.location.href
var parts = url.split("/")
var route = parts[parts.length-1]
if(route){
var link = $('a[href*="/'+route+'"]');
link.closest('ul').closest('li').addClass('active');
link.parent('li').addClass('active');
}
My current url is http://localhost/app/home
and I have this navigation :
<li class="dropdown">
<a href="#" class="nav-link has-dropdown" data-toggle="dropdown">
<i class="fas fa-list"></i>
<span>Outlook</span>
</a>
<ul class="dropdown-menu" style="display: block;">
<li><a class="nav-link" href="/home"><span>Sales</span></a></li>
<li><a class="nav-link" href="/"><span>Product</span></a></li>
<li><a class="nav-link" href="/"><span>Channel</span></a></li>
</ul>
</li>
What I expected:
<li class="dropdown active">
<a href="#" class="nav-link has-dropdown" data-toggle="dropdown">
<i class="fas fa-list"></i>
<span>Outlook</span>
</a>
<ul class="dropdown-menu" style="display: block;">
<li class="active"><a class="nav-link" href="/home"><span>Sales</span></a></li>
<li><a class="nav-link" href="/"><span>Product</span></a></li>
<li><a class="nav-link" href="/"><span>Channel</span></a></li>
</ul>
</li>
I need to add an active
class to the dropdown li
, and ul li
based on the current URL. Is there any simple solution with jQuery?
@NoobnSad: That is indeed correct. I assumed the