Reputation: 1269
I want to removeClass / addClass on click but since clicking also refresh the page it resets the html.
Any hint about how to solve this is really appreciated thanks.
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">All
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/category/C">CPU</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/category/R">RAM</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/category/G">GPU</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/category/CS">Case</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/category/HD">HardDisk</a>
</li>
</ul>
$(function() {
$('.nav-item').on('click', function() {
$('.nav-item.active').removeClass('active');
$(this).addClass('active');
})
});
Is there a way for the js function to fire after the page reload? Or any pratical way to accomplish the same result? thank's for everyone time and suggestions.
Upvotes: 0
Views: 1082
Reputation: 1368
Something like this should work.
$(document).ready(function() {
var current_path = window.location.pathname;
$("a.nav-link").each(function() {
var href = jQuery(this).attr("href");
if (current_path.includes(href) || if (href.includes(current_path) || href == current_path) {) {
$(this).parents(".nav-item").addClass('active');
}
});
});
Upvotes: 1
Reputation: 1403
As i get from your question, you can prevent of default behavior of a tag by js as you want in first section of your question by preventDefault()
function:
$(function() {
$('.nav-item').on('click', function(event) {
event.preventDefault();
$('.nav-item.active').removeClass('active');
$(this).addClass('active');
})
});
and for a function that fire after page reload you:
$(window).load(function(){
dosomething();
});
It will run the js after the whole page is loaded.
and finally i hope understand you question correctly.
Upvotes: 0
Reputation: 6742
you can't do this with Javascript, you have to use server side logic for this (php, java,...) Or you are using react/angular then you can use their built in logic for setting the active state of a link.
Upvotes: 0