To ensure the clicked button remains active, I utilize Bootstrap for seamless implementation

I have exhausted all possible methods to override the issue, including tweaking the CSS, but nothing seems to be working. I am currently utilizing bootstrap 5 for this project.

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a5a8a8b3b4b3b5a6b787f2e9f4e9f4">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73111c1c07000701120333465d405d40">[email protected]</a>/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>

Answer №1

When your buttons are enclosed in anchor tags pointing to different pages (href="/" and href="/Tasks"), clicking on them will lead the browser to navigate away, resulting in the active state not being visually preserved on the buttons.

While you could use preventDefault(), it might be more logical to avoid using the anchor tags altogether.

It is advisable to carefully consider the desired behavior and adjust your HTML structure accordingly.

Nevertheless, here is a code snippet that incorporates the functionality you desire utilizing preventDefault():

    document.addEventListener("DOMContentLoaded", function() {
  const notesButton = document.getElementById('notes');
  const tasksButton = document.getElementById('tasks');

  notesButton.addEventListener('click', function(event) {
    event.preventDefault();  // Prevent the page navigation
    notesButton.classList.add('active');
    tasksButton.classList.remove('active');
  });

  tasksButton.addEventListener('click', function(event) {
    event.preventDefault();  // Prevent the page navigation
    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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7974746f686f697a6b5b2e35283528">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26444949525552544756661308150815">[email protected]</a>/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>

Answer №2

You have been utilizing anchor tags to navigate to different pages. Therefore, it is essential to incorporate the preventDefault() method in the event listener. Refer to the example provided below:

document.addEventListener("DOMContentLoaded", function() {
  const notesButton = document.getElementById('notes');
  const tasksButton = document.getElementById('tasks');

  notesButton.addEventListener('click', function(e) {
    e.preventDefault();
    notesButton.classList.add('active');
    tasksButton.classList.remove('active');
  });

  tasksButton.addEventListener('click', function(e) {
    e.preventDefault();
    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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8defe2e2f9fef9ffecfdcdb8a3bea3be">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="03616c6c77707771627343362d302d30">[email protected]</a>/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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the background of a Muitextfield input element conceals the label

Struggling to customize the Textfield from the global theme? Can't seem to achieve a colored background for the input only (white) without obscuring the label when it moves inside the input. Desired result : https://i.sstatic.net/us2G7.png Current o ...

Creating a currency input field in HTML using a pattern textbox

In a project using HTML, Angular 2, and Typescript, I am working with a textbox. How can I ensure that it only accepts numbers along with either one dot or one comma? The input should allow for an infinite number of digits followed by a dot or a comma and ...

Adding Text Above a Material Icon in Angular: A Guide

Here is some sample HTML code to consider: <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <mat-icon class="fa fa-folder" style="font-size:48px;"><span style="color: re ...

When you click on links and buttons, a focus outline appears

I am currently troubleshooting an issue within an existing application that relies on the use of jQuery. The problem arises when I click on any link or button on the page, causing the element to display a focus outline (such as a blue glow in browsers like ...

What is the best way to align this list horizontally with evenly distributed widths?

I am struggling to figure out how to turn this into a horizontal list where all the elements have equal width. If there is any missing information, please let me know by commenting or messaging. All the CSS that is not within the "grid" <li> is for ...

Subclass Pseudoclass in JavaFX is a powerful feature that

I wanted to create two different styles of buttons in one css file. To achieve this, I added a class to the second button using: close.getStyleClass().add("close-button"); Now, I can reference this button in the css by: .button.close-button However, I ...

Display validation messages when the user either clicks out of the textbox or finishes typing

Here are some validation messages: <form name="dnaform" novalidate> <div style="padding-bottom:5px" ng-show="dnaform.uEmail.$pristine || dnaform.uEmail.$valid">Active directory account </div> <div style="padding-bottom:5px;" n ...

What are the ways in which RFC 2854 renders RFC 1867 outdated and irrelevant?

What is the reasoning behind RFC 2854 "obsoleting" RFC 1867? My confusion may arise from a lack of familiarity with how to interpret RFCs, but it seems that RFC 1867 explains the process of file uploading in HTML forms, while RFC 2854 discusses a MIME typ ...

Tips for resolving Layout Shift issues in responsive images utilizing the picture & source HTML tags

One issue I encountered with the <source> element is that even when specifying the width and height attributes for both the <source> and image fallback, there is still significant layout shift. This could be due to using images with varying dim ...

how can you make keyframe animation pause at the last stage?

Here is an example of utilizing CSS animations: .show-left-menu { -webkit-animation-name: leftSidebarAni; -webkit-animation-duration: .25s; -webkit-animation-timing-function: ease-out; -webkit-animation-iteration-count: 1; } @-webkit-keyframes l ...

Populate the table with JSON object information

I've structured a table as follows: <div class="row"> <div class="row"> <table class="table table-bordered table-striped tree-grid"> <thead class="text-primary"> <tr> <th> ...

jQuery causing trouble with AJAX in Rails

Currently, I am fetching a list of users from the controller side and generating the HTML code to append it. This is how I wrote the code: $.ajax({ type : "get", contentType : "application/json; charset=utf-8", url : "/users/sear ...

What is the correct way to format the headings for sub-level pages, like chapters within a novel or sections within a lengthy article?

At times, the text and image content becomes too expansive to fit on a single page. However, preserving the context of the content is crucial, making it necessary to display it explicitly from a user experience perspective. This could include chapters of a ...

Position the menu links in different alignments - some to the right and others to the

I have created a horizontal menu using HTML and CSS. Currently, the links (boxes) are displayed from left to right, floated to the left of the page. However, I am looking for a way to make one of the links (boxes) float to the right side of the page. I at ...

How can I prevent or override the text being pushed to the right by CSS::before?

Using the css property ::before, I am attempting to insert a tag before a paragraph. While I am able to display the tag correctly, it is causing the text within the paragraph to be shifted to the right. Ideally, I would like the tag to appear in the top-le ...

What is the best way to resize a div to fit its content if 'clear:both' and 'float:left' are not working as desired?

I've been struggling to find a solution for an issue with my HTML. I have three 'divs' that need to display different information in their own line, enclosed in a parent element with a centered border. Despite trying solutions like inline-bl ...

Selectize-dropdown menu shines brightly as it opens upwards

In my sleek dashboard design, I have implemented a few dropdown menus using selectizeInput. These menus are currently positioned at the bottom of the page, but I want them to open in an upward direction instead of downward. While I found a workaround for ...

Flexbox wrap allows you to determine which child element will move to the next line

Is there a way to control which child element in flexbox drops to the next line, instead of just the last one every time? For example: Full-size, no breaking: https://i.sstatic.net/proUB.png Default behavior, breaking the last element: https://i.sstatic.n ...

Passing parameters from an HTML form using PHP

I have a background in C# and am still relatively new to PHP. I have an HTML form that submits its values to the PHP file below, but for some reason, the values are not being set. Can you help me identify what I'm doing wrong? <?php include(' ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...