Activate my Bootstrap navbar links using only JavaScript code

I am currently working on a project where I want my navbar links to become active when clicked. My initial thought is to add the 'active' class when a link is clicked, but I'm unsure how to ensure that only one link is active at a time. Additionally, I am having trouble getting the code to run after the HTML has loaded, causing it not to work as expected.

let links = document.querySelectorAll('.nav-link');

links.addEventListener('click', function() {
    this.classList.add('active');
});

I have tried using the above code to make the link active, but it doesn't seem to execute after the HTML has loaded, resulting in the desired effect not being achieved.

Link to JSFiddle for reference

TL;DR

  • Struggling with removing active class from currently active link using JS
  • Code for making clicked link active loads prior to HTML rendering, causing issues

Answer №1

Take a look at this code snippet:

let links = document.querySelectorAll('.nav-link');
for(let i=0; i<links.length; i++){
  links[i].addEventListener('click', function() {
    for(let j=0; j<links.length; j++)
      links[j].classList.remove('active');
    this.classList.add('active');
  });
}
body {
  background: linear-gradient(0.1turn, #673fa6, #e1f5f8, #f6c43c);
}

nav {
  opacity: 0.8;
}

.text-shadow {
  text-shadow: 5px 5px 15px;
}
<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <!-- My CSS -->
  <link rel="stylesheet" href="styles/style.css">

  <title>Justice Dunn</title>
</head>
<body>
  <nav class="navbar navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">
      <img src="node_modules/bootstrap-icons/icons/kanban-fill.svg" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy">
      Justice Dunn
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link active" href="#bg1">Home</a>
        <a class="nav-link" href="#bg2">Background</a>
        <a class="nav-link" href="#bg3">Hobbies</a>
        <a class="nav-link" href="#bg4">Achievements</a>
        <a class="nav-link" href="#bg5">The Future</a>
        <a class="nav-link" href="#bg6">Gallery</a>
      </div>
    </div>
  </nav>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg1">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-shadow display-3">Hello!</h1>
      <p class="text-center text-shadow h4">I'm Justice Dunn, a 19-year-old developer in Cheyenne, Wyoming.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg2">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Background</h1>
      <p class="text-center text-black mt-3 h5">I decided that I wanted to become a developer for a few reasons.</p>
      <p class="text-center text-black mt-3 h5">I've always been a creative person, and I've always enjoyed problem solving. Being a developer just seems to be an occupation that naturally incorporates both of those things.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg3">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Hobbies</h1>
      <p>Writing Music</p>
      <p>Digital Art</p>
      <p>3D Modeling</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg4">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Achievements</h1>
      <p class="text-center h5 mt-3">I don't have a lot of life experience yet, so I'd say my greatest achievement was getting accepted into the Array apprenticeship program!</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg5">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">The Future</h1>
      <p class="text-center h5 mt-3">After this Array apprenticeship, I want to begin developing apps and write, record, and produce an album.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg6">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Gallery</h1>
      
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS and local JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62b6a9b7b7a2b5e99dbabdafbaabaefbab">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  <script src="/scripts/script.js"></script>
</body>
</html>

We're implementing a click event listener on every element with the class .nav-link. When clicked, it removes the .active class from all elements and adds the .active class to the clicked element.

Answer №2

Another method you could attempt is by avoiding the use of a loop with each load.

  document.body.addEventListener('click', function(e) {
  if(e.target.className==='nav-link'){
      document.getElementsByClassName('nav-link active')[0].classList.remove('active');
     e.target.classList.add('active');
     }
  });
body {
  background: linear-gradient(0.1turn, #673fa6, #e1f5f8, #f6c43c);
}

nav {
  opacity: 0.8;
}

.text-shadow {
  text-shadow: 5px 5px 15px;
}
<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <!-- My CSS -->
  <link rel="stylesheet" href="styles/style.css">

  <title>Justice Dunn</title>
</head>
<body>
  <nav class="navbar navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">
      <img src="node_modules/bootstrap-icons/icons/kanban-fill.svg" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy">
      Justice Dunn
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link active" href="#bg1">Home</a>
        <a class="nav-link" href="#bg2">Background</a>
        <a class="nav-link" href="#bg3">Hobbies</a>
        <a class="nav-link" href="#bg4">Achievements</a>
        <a class="nav-link" href="#bg5">The Future</a>
        <a class="nav-link" href="#bg6">Gallery</a>
      </div>
    </div>
  </nav>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg1">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-shadow display-3">Hello!</h1>
      <p class="text-center text-shadow h4">I'm Justice Dunn, a 19-year-old developer in Cheyenne, Wyoming.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg2">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Background</h1>
      <p class="text-center text-black mt-3 h5">I decided that I wanted to become a developer for a few reasons.</p>
      <p class="text-center text-black mt-3 h5">I've always been a creative person, and I've always enjoyed problem solving. Being a developer just seems to be an occupation that naturally incorporates both of those things.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg3">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Hobbies</h1>
      <p>Writing Music</p>
      <p>Digital Art</p>
      <p>3D Modeling</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg4">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Achievements</h1>
      <p class="text-center h5 mt-3">I don't have a lot of life experience yet, so I'd say my greatest achievement was getting accepted into the Array apprenticeship program!</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg5">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">The Future</h1>
      <p class="text-center h5 mt-3">After this Array apprenticeship, I want to begin developing apps and write, record, and produce an album.</p>
    </div>
  </div>

  <div class="container vh-100 vw-100 d-flex align-items-center" id="bg6">
    <div class="container d-flex-inline justify-content-center">
      <h1 class="text-center text-black text-shadow display-3">Gallery</h1>
      
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS and local JS -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37475847475245195d4477061906011906">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  <script src="/scripts/script.js"></script>
</body>
</html>

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

After completing a sequence, it does not reset

I'm working on creating a versatile "slideshow" feature that can be used for various elements. Currently, I am testing it on a div that contains paragraph text taken from my HTML document and represented as container1, container2, and container3. The ...

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

Receiving an error message stating "Uncaught SyntaxError: Unexpected token <" in React while utilizing the AWS SDK

Each time I execute 'npm run build' in main.js, an error keeps popping up: Uncaught SyntaxError: Unexpected token < The error vanishes after refreshing the page. Upon investigation, I discovered that two libraries are causing this problem: ...

Preserve the Browser Scroll Position when navigating to another page

Currently tackling a challenge with JS, JQuery, and PHP where I'm attempting to resolve an infinite scroll issue. The specific problem arises when scrolling down the page extensively while loading more pages via ajax, then navigating to a different pa ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Is there a way to link a Twitter handle with Angular UI Router?

Can anyone help me with finding the correct regex to match a path like '/@someusername' with angular ui router? I've been struggling to figure it out. Currently, my routes look like this $stateProvider .state('home', {url:'/ ...

Output the word 'Days', 'Months', or 'Years' depending on the value of N, which represents the number of days

I am currently utilizing moment.js in conjunction with vue 3. I've implemented a function that calculates the disparity between two dates. The functionality works as expected, but here's where my query comes in. The function is structured like so ...

Is there a way to determine if the current path in React Router Dom v6 matches a specific pattern?

I have the following paths: export const ACCOUNT_PORTAL_PATHS = [ 'home/*', 'my-care/*', 'chats/*', 'profile/*', 'programs/*', 'completion/*', ] If the cur ...

What steps do I need to follow to write this function in TypeScript?

I am encountering a problem when building the project where it shows errors in 2 functions. Can someone please assist me? The first error message is as follows: Argument of type 'IFilmCard[] | undefined' is not assignable to parameter of type &a ...

Tips for altering the class of an HTML button dynamically when it's clicked during runtime

I currently have a set of buttons in my HTML page: <button id="button1" onclick="myFunction()" class="buttonClassA"></button> <button id="button2" onclick="myFunction()" class="buttonClassA"></button> <button id="button3" onclic ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Unable to provide desired array return

Greetings from a newcomer to StackExchange! I recently delved into the world of programming and am currently learning JavaScript. My goal is to create an array of random numbers with 'n' size in order to experiment with sorting and searching algo ...

Restricted information causes disruption in the PHP web design

I encountered a problem when attempting to limit the content of description. Here is what I tried: <?php $intDescLt = 400; $content = $arrContentList[$arr->nid]['description']; $excerpt = substr($content, 0, $intDescLt); ?> <div ...

Angular 8 offers the functionality of a mat-dialog that is both draggable and resizable, providing

In search of a solution to enable both dragging and resizing for a mat-dialog. I have successfully implemented the dragging functionality using cdkDrag (DragDropModule). However, when trying to use resize: booth; in CSS, it seems to conflict with the dragg ...

One way to display a div's inner HTML as its background is to apply a CSS rule

Help needed! <div class="container">red</div> <div class="container">green</div> <div class="container">#eeeeee</div> I am trying to dynamically set background colors for multiple divs based on their inner HTML co ...

How can JavaScript effectively retrieve the JPEG comment from a JPEG file?

How can one properly retrieve the JPEG comment field (not EXIF, but the COM field) from a JPEG file using JavaScript, particularly when running node on the command line? While there are several libraries available for reading EXIF data in JavaScript, I ha ...

Automate web tasks with C# WebBrowser

Currently, I am in the initial phases of developing a system to automate the process of data extraction and collection from a website. I have a massive CSV file containing 16,000 lines of data. My goal is to input data from each line into a textarea on a w ...

Browserify Rails encountered an error - ParseError: Error with 'import' and 'export'. These statements can only appear with 'sourceType: module'

Recently, I encountered an issue while trying to integrate an NPM package into my Rails application. The problem I'm facing can be seen in the following image: https://i.stack.imgur.com/cIOw8.png I searched this forum for similar issues but found tha ...

How to Extract Content from a Different Website Using jQuery's $.post() Function

When using the load() method in jQuery, you can retrieve a specific part based on a class or ID of an element. For example: $( "#result" ).load( "ajax/test.html #container" ); This code snippet will load the content found within the #container element. N ...