I want to have a jQuery dynamic menu that navigates to the <a></a>
tags and the one that include with the page URL.
$('ul.nav.navbar-nav.side-nav.nicescroll-bar li').find('a').each(function() {
var text = $(this).attr("href");
if (window.location.href.includes(text)) {
$('ul.nav.navbar-nav.side-nav.nicescroll-bar li a').addClass('active')
} else {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;">
<li><a href="home">home</a></li>
<li><a href="dashboard">dashboard</a></li>
<li><a href="base">base</a></li>
<li><a href="test">test</a></li>
</ul>
In this code, there is a color change in all menus, which should change the color of the menu according to the page's address.
Just remove the class in else:
if (window.location.href.includes(text)) {
$(this).addClass('active')
} else {
$(this).removeClass('active')
}
Change
if (window.location.href.includes(text)) {
$('ul.nav.navbar-nav.side-nav.nicescroll-bar li a').addClass('active')
}
into
if (window.location.href.includes(text)) {
$(this).addClass('active')
}
It works when you use this to add the class. I changed one href to stack because the href of the snippet is something like stacksnippet. For that element it colors red.
$('ul.nav.navbar-nav.side-nav.nicescroll-bar li').find('a').each(function() {
var text = $(this).attr("href");
if (window.location.href.includes(text)) {
$(this).addClass('active')
}
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;">
<li><a href="home">home</a></li>
<li><a href="dashboard">dashboard</a></li>
<li><a href="stack">base</a></li>
<li><a href="test">test</a></li>
</ul>
You can simplify your selector and code and use .filter()
instead of .each()
$('ul.navbar-nav li a').filter(function(){
return window.location.href.includes($(this).attr('href'));
}).addClass('active');
window.location.href = "#home";
$('ul.navbar-nav li a').filter(function(){
return window.location.href.includes($(this).attr('href'));
}).addClass('active');
.active {color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;">
<li><a href="home">home</a></li>
<li><a href="dashboard">dashboard</a></li>
<li><a href="base">base</a></li>
<li><a href="test">test</a></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With