I'm currently working on creating a Navbar and implementing the navbar highlighting feature using the active
bootstrap class.
Below is the code I have tried:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel='icon' type='image/x-icon' href='static/images/logo.png'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>FIFA Automation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="collapse navbar-collapse flex-grow-1 text-right">
<ul class="navbar-nav ms-auto flex-nowrap">
<li class="nav-item active">
<a class="nav-link external" href="/home" data-toggle="tab">Home</a>
</li>
<li class="nav-item">
<a class="nav-link external" href="/about" data-toggle="tab">About us</a>
</li>
</ul>
</div>
</nav>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
crossorigin="anonymous"></script>
</body>
</html>
JS file:
<script>
$(document).ready(function () {
$(".navbar-nav .nav-link").click(function (e) {
e.preventDefault();
$('.nav-item').removeClass('active');
$(this).closest('.nav-item').addClass('active');
});
});
</script>
Included e.preventDefault();
to highlight the navbar, but this causes redirection to the href
link not to work as expected.
If I remove this line, the redirection works but the navbar highlighting doesn't. How can I solve this dilemma?