Even though I tried every method it does not seem to override. I tried a lot of different methods like fiddling with CSS but nothing seems to work. I am using bootstrap 5
document.addEventListener("DOMContentLoaded", function() {
const notesButton = document.getElementById('notes');
const tasksButton = document.getElementById('tasks');
notesButton.addEventListener('click', function() {
notesButton.classList.add('active');
tasksButton.classList.remove('active');
});
tasksButton.addEventListener('click', function() {
tasksButton.classList.add('active');
notesButton.classList.remove('active');
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles/main.css" />
<title>Trackz</title>
</head>
<header>
<div class="container-fluid mt-3">
<nav class="navbar tabar mx-5">
<div class="container-fluid">
<a class="navbar-brand mx-4 text_color" href="/">
Trackz
</a>
<div class="d-flex">
<a href="/"><button class="btn btn-outline-light mx-2" id="notes">Notes</button></a>
<a href="/Tasks"><button class="btn btn-outline-light mx-2" id="tasks">Tasks</button></a>
</div>
</div>
</nav>
</div>
</header>
2
Answers
Since your buttons are wrapped in anchor tags that navigate to different pages (
href="/"
andhref="/Tasks"
), clicking them will naturally cause the browser to navigate away, thus not preserving the active state visually on the buttons.You can use
preventDefault()
, but it does not make sense since you can rather not use the anchor tags at all.I would highly recommend to brainstorm the behaviour you want to achieve and based on that change your HTML structure.
Anyway here is a snippet that adds the feature you are after with
preventDefault()
You are using anchor tags navigate to different pages. So you have to use
preventDefault()
on the event listener. Check Example below: