Implementing the active class in a Bootstrap navbar

When using jQuery to initialize the active class from navigation, I have encountered an issue. The code only works if there is nothing else after the menu item in the URL.

For example, when I visit the users page like this: site.com/users, the code functions properly. However, if I navigate to a controller with parameters like this: site.com/users/param1/param2, the active class disappears.

Below is the code I am currently using:

$(document).ready(function () {
    var url = window.location;
    
    // Will only work if string in href matches with location
    $('ul.nav a[href="' + url + '"]').parent().addClass('active');

    // Will also work for relative and absolute hrefs
    $('ul.nav a').filter(function () {
        return this.href == url;
    }).parent().addClass('active').parent().parent().addClass('active');
});

Answer №1

Assume you have URLs structured like this: /AAA/BBB/CCC/..... By using this code, your links will be able to recognize all variations such as /AAA/BBB/..., /AAA/XXX/...., and others as the same page.

$(document).ready(function () {
    var url = window.location;

    // This code snippet will break down your URL into parts stored in an array
    var urlParts = url.split("/"); 

    // This line is specifically designed for links like /AAA
    $('ul.nav a[href="' + urlParts[0] + '"]').parent().addClass('active');

    // Since the previous line may not cover all cases, custom filters are needed
    $('ul.nav a').filter(function () {
        var hrefParts = this.href.split("/");
        return hrefParts[0]==urlParts[0]; 
        // Make sure to adjust 0 or 1 depending on your link format (e.g., /AAA/ or AAA)
        // If your links use absolute paths, additional adjustments will be required.
    }).parent().addClass('active').parent().parent().addClass('active');
});

Update: The code should work now, but feel free to experiment with it. Keep in mind that customization may be necessary based on the types of links used in your specific situation.

Answer №2

Give this a shot:

$('ul.nav a').filter(function () {
        return url.href.indexOf(this.href) >= 0;
    }).parent().addClass('active').parent().parent().addClass('active');

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

What is the best way to set unique heights for various ion-grid components?

Situation: I am facing an issue with my Ionic/Angular app. The screen layout, as shown in the image provided and on Stackblitz, includes two ion-grids with different background colors - green and red. Goal: My goal is to assign a percentage height to each ...

Transform ternary conditional operators into if-else statements

I encountered an issue while attempting to convert a simple minified jQuery code to an if else statement. The error message "Can't find variable: i" is displayed. Check out the original code below: var c = slider.activeIndex; 0 === c ? (slider.slid ...

Adjusting the gridview headers to line up with a specific item and shifting the content of the item to the right

I am struggling with aligning the header and content in my gridview. I want the shirts to be underneath the header item, with the description moved to the left and the price 336 moved to the right. Something like this: https://i.sstatic.net/2i2IR.png Her ...

Arrange flexbox containers side by side in a horizontal row

I am attempting to create two flexbox containers one after the other, utilizing a combination of classes to achieve this layout. While the flexbox is created successfully, I encounter an issue where the lower container goes below the upper one when scrolli ...

Find the flowplayer when the page loads

Is there a way to make a flowplayer seek at the page load without it resetting? I've tried this: $(document).ready(function() { $f(0).seek(5); }); also tried: $(document).ready(function() { while(!$f(0).isLoaded()) { $f(0).seek(5); } }); ...

Instructions on dynamically positioning a collection of div elements at the center of a webpage container

I am looking to create a set of divs that are centered on the page and adjust in size according to the length of the username. .Container1 { display: table; width: 100%; padding:0; margin:0; -webkit-box-sizing: border-box; -moz-box-sizing: bor ...

Issue with :visited pseudo-class not functioning as intended

My code includes all four basic pseudo-classes, and they all seem to be working fine except for the :visited pseudo-class. The color property doesn't function properly, and the background property appears to be inactive. I'm not sure what the iss ...

Show fixed position buttons

My Angular HTML form includes a grid setup, defined as follows: .grid { display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 2%; grid-auto-rows: 90%; } This grid creates two parallel rectangles. I have divs ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Organizing various elements into separate divs with just one ajax request

I recently encountered an issue with my project involving an ajax call that was functioning correctly. $.get( 'accNoRealMovs1.jsp', {mode:"0"}, function(responseText){ $('#divAccMovementNR').html(responseTe ...

tips for managing the backspace key in the key up event handling

I have a record stored in a database with the names Charles, Dale, Jack, and William. Using PHP code, I am able to retrieve this data from the database and display it initially. I have also added a text field where any of these four names can be entered, a ...

The div inside another div does not appear centered on Safari

Even though I've managed to center a div within another div, it seems to not be functioning properly in the Safari browser. #box{ width: 100%; height: 100%; position: relative; } ...

Attempting to shift an element without relying on the use of position:relative

I'm trying to figure out if I can relocate this (image1) to (image2). I prefer not to utilize position:relative as it may disrupt my design in bootstrap. Image 1 (I don't want it here) Image 2 ( I want it here) Here is the relevant CSS code: ...

Automatically scroll the element both up and down

I am working on a bootstrap table that needs to automatically scroll vertically. The table will be displayed on a screen and could have varying numbers of items, so I want it to continuously auto-scroll for the user's convenience. Once it reaches the ...

Nested loops displaying modal when button is clicked - Utilizing JQuery and Ajax

I'm facing a challenge with 3 questions all related to the same issue that I need help solving: 1 How can I create a loop within another loop to extract price_history from a .json file and display the 7 results inside the modal using the template sto ...

What is the best way to make a table fill 100% of the available height

Is this a Repetitive Question? How to stretch an HTML table to 100% of the browser window height? Just like the title says, I am looking for a way to make my table element stretch to 100% height even when the content does not entirely fill the page&ap ...

Enhance your website with interactive AJAX callback animations using jQuery

I've encountered an issue while using a basic AJAX script in jQuery. I want to implement an easeInOut effect for the AJAX callback to change the HTML smoothly, but I'm not sure how to achieve this. Currently, when the response is received, the co ...

Utilize the :not() and :hover selectors in Less when styling with CSS

Some of my elements have a specific class called .option, while others also have an additional class named .selected. I want to add some style definition for the :hover state on the .option elements, but only for those without the .selected class. I' ...

Customizing Navbar or other elements in react-bootstrap

While working on my react project, I have been using react-bootstrap. However, I am interested in delving deeper into all the features that this framework has to offer. I have come across pages supported by react-bootstrap and even downloaded templates, bu ...

Omitting items from the duplicated text on Safari

I am looking for a way to allow users to copy and paste a block of text without including inline controls, such as buttons. In Chrome, adding user-select: none; to the controls achieves this. When the user selects the entire paragraph, the buttons are not ...