I was working on my app and had this jQuery code that adds active class on current location which is working just fine.
Now my problem is that I need to know how to set a default or I should say place the active class on Home link whenever there is no link selected or the URL is http://localhost:3000/
var url = window.location.href;
var link = window.location.hash
$('a.ks-nav.active-menu').removeClass('active');
$('a.ks-nav[data-id="' + link.replace('#', '') + '"]').addClass('active');
Here are my links:
<a class="nav-link ks-nav" data-id="home" href="/#home">Home</a>
<a class="nav-link ks-nav" data-id="about" href="/#about">About</a>
<a class="nav-link ks-nav" data-id="contact" href="/#contact">Contact</a>
How can I set a jQuery default code that adds the active class on Home whenever there are no setup active class on any of the available menu? This needs a deeper checking and make sure there are no other element that has the class cause basically when they click on a different menu the Home link must remove the active class and will go to that link URL / click menu.
Please help!
You can use length property of the jQuery object like this:
var url = window.location.href;
var link = window.location.hash
var linkTag = $('a.ks-nav[data-id="' + link.replace('#', '') + '"]');
if (linkTag.length) {
linkTag.addClass('active');
} else {
$('.ks-nav[data-id="home"]').addClass('active');
}
.ks-nav.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="nav-link ks-nav" data-id="home" href="/#home">Home</a>
<a class="nav-link ks-nav" data-id="about" href="/#about">About</a>
<a class="nav-link ks-nav" data-id="contact" href="/#contact">Contact</a>
Just change in your HTML:
<a class="active nav-link ks-nav" data-id="home" href="/#home">Home</a>
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