What is the best way to highlight the current navbar element in Bootstrap and ensure it remains active even after the screen is refreshed?

In my web application, I have a navbar that navigates to different pages.

<nav class="navbar navbar-expand-md sticky-top navbar-ligth bg-fadded">
            <a class="nav-link waves-effect waves-light" th:href="@{/}">
                <img class="home-logo" alt="UTL-2" th:src="@{/static/img/site-logo.png}"/></a>
            <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent">
                <ul id="myDIV" class="navbar-nav mr-auto">
                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/login}">Login
                            <span class="sr-only">(current)</span></a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/plan}">Plan</a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/orders}">Orders</a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/stations}">Stations</a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/partner}">Partners</a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/map}">Map</a>
                    </li>

                    <li class="nav-item">
                        <a class="nav-link waves-effect waves-light" th:href="@{/info}">Info</a>
                    </li>

                </ul>

            </div>
        </nav>

To apply the "active" class to a nav-item when clicked, I use this simple script:

<script>
            var btnContainer = document.getElementById("myDIV");
            var btns = btnContainer.getElementsByClassName("nav-item");

            for (var i = 0; i < btns.length; i++) {
                btns[i].addEventListener("click", function() {
                    var current = document.getElementsByClassName("active");
                    if (current.length > 0) {
                        current[0].className = current[0].className.replace(" active", "");
                    }
                    this.className += " active";
                });
            }
        </script>

While this script works on static pages, when navigating to another page the element loses the "active" class. Is there a way to only update the body of the webpage or mark elements differently? How does this work in Bootstrap?

I found a solution using Thymeleaf, but how can I retrieve the current active link: th:classappend="${module == 'login' ? 'active' : ''}" What is the correct element that can return the current link?

Answer №1

After digging around for an hour trying to find a simple solution, I ended up writing this script:

<script>
        var currentPage = window.location.pathname;
        var items = document.getElementById("myDIV").getElementsByClassName("nav-item");
        var activeClass = "active";

        var patt = new RegExp(currentPage.split("/")[1],"i");

        for(var i = 0; i < items.length; i++){
            var navItem = items[i];
            var linkArray = navItem.children[0].href.split("/");
            var linkHTML = linkArray[linkArray.length - 1];
            if(patt.test(linkHTML)){
                navItem.classList.add("active");
            }
        }
    </script>

While this script does the job, it seems unlikely that there isn't a more built-in solution in thymeleaf or bootstrap for this task.

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

Is it necessary to add a line break after a span element generated by react, next, or bootstrap

There is a strange issue plaguing my code - I'm enclosing some text in a span tag and it's causing an unexpected line break. It's unclear whether React.js, Next.js, or Bootstrap is the culprit, but I can't seem to get rid of the pesky l ...

Tips for Updating Multiple Textareas (containing HTML content of up to 4000 characters) within an HTML Form when the Form Button is Clicked

In my PHP script, I am storing data in a two-dimensional array. Here are some sample values from the PHP array: First Element in Array ID = 1 QUES= <p>ABCD</p> OPT_A = <p>A</p> OPT_B = <p>B</p> Second Element in Array ...

Tips for controlling input elements with bootstrap

The sequence of the add more btn in jQuery input seems to be random, but I want it to be in a specific order. Current Output: https://i.sstatic.net/mGfPT.png Desired Output: https://i.sstatic.net/L5GTm.png ...

How can I modify the appearance and behavior of an HTML button?

I simply need to update the button class and value in order to change the button's functionality. After successfully changing the value and class, the functionality remains the same as the old class. Why is this happening? Could it be that the brows ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Is your Facebook send button appearing strangely? Find out how to fix it here!

I recently integrated the Facebook send button on my website, allowing users to easily share information about each drive listed. However, a new issue has arisen where clicking on the send button opens a popup inside a table, negatively affecting the page& ...

Angular material raised button with the file input feature for versions 4 and 5

I am currently developing an Angular application and for file upload, I am using the following code snippet: <label class="btn btn-default"> <input type="file" (change)="selectFile($event)"> </label> <button class="btn btn-success ...

Strategies for Concealing an Image When CSS is Active in Internet Explorer

My login functionality includes an input box with a CSS image that disappears onclick, allowing users to enter information. I used an image because the text password displays as "*", but this setup is not working in IE. Can anyone assist? HTML: <form ...

The loading of Bootstrap was halted by WAMP

Hi there, I'm encountering some issues with my WAMP setup. Previously, my pages were loading fine on WAMP, but a few months back, I attempted to use a keyboard shortcut to refresh a tab on Chrome. After that, my Bootstrap stopped loading. Everything w ...

Steps for dynamically generating rows in an HTML table using information extracted from a database

Hey everyone, I have a MySQL database table named "mezziDiTrasporto" with multiple rows of data. I am trying to create a new table that will automatically populate rows with data from the database table whenever a SELECT query is executed. Is this achievab ...

AngularJS - Dynamically change the placeholder value

<md-input-container class="md-block hide-error-space" flex="25"> <input required name="password" ng-model="password"> </md-input-container> Here is a form field where the user can enter their password. <md-input-container md-no-float ...

Detection of numerous Google Analytics tags

To troubleshoot a client's Google Analytics account connected to their website, I decided to utilize the Tag assistant by Google extension. Upon running it, an alert popped up displaying "Multiple Google Analytics tags detected." One tag was the one I ...

JS and MUI are combining forces to create a dynamic background change on the page when selecting items from a dropdown menu

I encountered an unusual issue on my website that appears to be related to the UI library I am using. Whenever I click on a select element, the background undergoes a slight change in width, causing the background image to flicker. Initially, I assumed thi ...

What are some strategies to enhance the responsiveness of this JQuery code?

I'm facing an issue while trying to create a progress bar that dynamically adjusts based on the device's width. In this particular scenario, whenever the device width changes, the progress bar's width remains static, causing it to break whe ...

Exploring nodes with the help of Cheerio JS

In my HTML code, I am using the Snekfetch library to fetch data. Here is a snippet of the code: <div class="entry-content"> <h4>today's date etc etc</h4> <h3>category name 1</h3> <p> <img class=" ...

Automatic width table design

I am trying to position the "User ID" label closer to its value by aligning it to the right side, as shown in the picture below. I have attempted using additional colspan's but haven't been successful. The User ID can contain anywhere from 1 to 9 ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

Determine the execution time of a Python script

I have developed a series of Python scripts to run as the backend of my application. Users are required to upload a file using the provided webpage, where they can track the progress through a displayed progress bar. The file is broken down into frames, ob ...

Tips for aligning the navigation bar, main content, and footer in the center

Exploring the realm of web coding for the first time, I find myself in need of some guidance. My current project involves creating a webpage for the local sports team to replace their outdated one on Wordpress. Finding the platform not very user-friendly, ...

Polymer event / callback for appending new child nodes

My current project involves creating a custom element, let's call it <parent-element>, that performs specific actions based on the presence of its childNodes. When I define the element like this: <parent-element> <div> </div&g ...