I have been trying various methods, but I am unable to change the background color of an active navigation item and also display the corresponding page.
Important: The jQuery code below successfully changes the background color of the navbar list item. However, whenever I click on the page, it reverts back to the default color. If I include 'e.preventDefault()', the background color changes correctly but the page relative to the navbar item does not display.
HTML (EJS file)
<div class="navbar-nav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Item 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 4</a>
</li>
</ul>
</div>
CSS
.navbar-nav > .aMenuActive {
background-color: var(--main-pink-color);
}
JQuery
// aMenuActive -> Add class to clicked li
$('ul.navbar-nav > li').click(function (e) {
console.log("log...clicked menu",);
$('ul.navbar-nav > li').removeClass('aMenuActive');
$(this).addClass('aMenuActive');
//e.preventDefault(); // -> works but does not send to link
});
$('ul.navbar-nav > li').click(function (e) {
console.log("log...clicked menu",);
$('ul.navbar-nav > li').removeClass('aMenuActive');
$(this).addClass('aMenuActive');
//e.preventDefault(); // -> works but does not send to link
});
.navbar-nav > .aMenuActive {
background-color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar-nav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Item 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Item 4</a>
</li>
</ul>
</div>