Reputation: 1
Hii I am new to jquery and I want to add/remove the active class to/from the li tag until the other link is clicked for navigation. Currently, I am using the same navigation for all of my Html pages.
This is my index.html file
<body>
<div id="nav_bar">
<!-- <a href="navigation/navigation.html">link</a> -->
</div>
<script>
$(function() {
$("#nav_bar").load("navigation/navigation.html");
});
</script>
</body>
I've applied the same method for other Html files to and it is working fine.
Navgation.html
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light justify-content-end " id="nav_global ">
<button class="navbar-toggler " type="button " data-toggle="collapse " data-target="#navbarNav" aria-controls="navbarNav " aria-expanded="false " aria-label="Toggle navigation ">
<span class="navbar-toggler-icon "></span>
</button>
<div class="collapse navbar-collapse " id="navbarNav ">
<ul class="nav navbar-nav mr-auto ">
<li class="nav-item active" id="home ">
<a class="nav-link " href="/assignment/index.html ">Home</a>
</li>
<li class="nav-item " id="assignment ">
<a class="nav-link " href="/assignment/assign/assignment.html ">Assignment</a >
</li>
</ul>
</div>
</nav>
<script>
alert("hello from script ");
$("li.nav-item").click(function(event) {
let someVar = $(this).hasClass("active");
alert(someVar);
if (someVar == false) {
$("li.nav-item").each(function(i) {
$(this).removeClass("active");
});
$(this).addClass("active");
}
});
</script>
</body>
Now the problem is when I click a link and after the alert is shown the changes are reverting back immediately means that the home is getting active again even after using the removeClass(). Somehow the changes made to the clicked links by addClass are temporarily resulting in the home getting active again. I've used both return false and event.preventDefault() but it is preventing my link to open which I don't want.
I want to make the clicked link li class be active.
ps: sorry for my bad English and explanation. Please feel free to correct my question If you find some error.
Thank you
Upvotes: 0
Views: 99
Reputation: 24965
Taking just the two links you have in your OP, here is what I would suggest attempting.
<script>
$( () => {
const data = [
{ suffix: '/index.html', selector: '#home' },
{ suffix: '/assignment.html', selector: '#assignment' }
];
const currentPage = data.find( it =>
window.location.href.endsWith( it.suffix )
);
if ( currentPage ) {
$( currentPage.selector ).addClass( 'active' );
}
} );
</script>
On document ready, you create a list of maps, creating a relationship between the url for each page, and the selector for the link to that page. Then you can find the relationship based on the current url, and if you find one, lookup the link and put the active class on it.
Upvotes: 0