Make Twitter Bootstrap Navbar Link Active

Make Twitter Bootstrap navbar link active

You need to ensure that you set the active class as part of the request response (as the page loads) and not before ie when the user clicks a link to request a different page.

First you need to determine which navlink should be set as active and then add the active class to the <li>. The code would look something like this

Tested by asker:

HTML within php file

Call a php function inline within the <li> markup passing in the links destination request uri

<ul class="nav">
<li <?=echoActiveClassIfRequestMatches("home")?>>
<a href="home.php">Search</a></li>
<li <?=echoActiveClassIfRequestMatches("about")?>>
<a href="about.php">About</a></li>
</ul>

PHP function

The php function simple needs to compare the passed in request uri and if it matches the current page being rendered output active class

<?php 

function echoActiveClassIfRequestMatches($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");

if ($current_file_name == $requestUri)
echo 'class="active"';
}

?>

How to get Twitter-Bootstrap navigation to show active link?

Just made an answer on the very same question here
Twitter Bootstrap Pills with Rails 3.2.2

<ul class="nav">
<li class="<%= 'active' if params[:controller] == 'controller1' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller2' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller3' %>"> <a href="/link">Link</a> </li>
</ul>

bootstrap4 navbar set active link

Bootstrap documentation says:

Active states—with .active—to indicate the current page can be applied
directly to .nav-links or their immediate parent .nav-items.

So you need to place active class on nav-item to make it work. Like this:

<nav class="navbar navbar-expand-sm"> <button class="navbar-toggler" type="button" data-target="#navigation"> <span class="navbar-toggler-icon"></span> </button>
<div class="collapse navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item active"> <a href="{% url 'terminal-management' %}" class="nav-link"> Terminals </a> </li>
<li class="nav-item"> <a href="{% url 'location-management' %}" class="nav-link active"> Area & Rooms </a> </li>
</ul>
</div>
</nav>

Probably you won't need to define a custom style to it, but you can using this css selector:

.nav-link.active {
color: red;
}

How do I make Bootstrap navbar change active state?

You can do this one an the end of your code. Just below <script src="main.js"></script>

<script>
$(document).ready(function() {
$( ".mr-auto .nav-item" ).bind( "click", function(event) {
event.preventDefault();
var clickedItem = $( this );
$( ".mr-auto .nav-item" ).each( function() {
$( this ).removeClass( "active" );
});
clickedItem.addClass( "active" );
});
});
</script>

And them instead of follow by link (event.preventDefault()) eg. about.html OR uploads.html this snipet of code change active class for clicked item.


EDIT 1:

For static pages (or served eg. by php) you don't need any aditional js code, BUT you should tweak nav to looks like in below examples (look where 'active' class is, sr-only span current is optional, but well placed in examples).

index.html (your base code)

<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="index.html">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="library.html">Library</a>
</li>
<li class="nav-item">
<a class="nav-link" href="uploads.html">Uploads</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About</a>
</li>
</ul>

library.html

<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="library.html">Library<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="uploads.html">Uploads</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About</a>
</li>
</ul>

uploads.html

<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="library.html">Library</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="uploads.html">Uploads<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About</a>
</li>
</ul>

about.html

<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="library.html">Library</a>
</li>
<li class="nav-item">
<a class="nav-link" href="uploads.html">Uploads</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="about.html">About<span class="sr-only">(current)</span></a>
</li>
</ul>

Set my Bootstrap navbar links to be active (with pure JavaScript)

Check out this 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="Sample Image" 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/popper.js@1.16.1/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>

Bootstrap Navbar Active State Switching Bootstrap (Javascript Related)

You dont appear to have an ancestor to the nav list with the class of "nav" - also the nav-link li's are what should get the 'active' class - not the 'a' within it.

Also - you can target the active item directly to remove the active class - whether its the li or the a.

if you want to keep the active class on the a - then just change the click handler

$(".nav-link").on("click", function(){
$(".nav-link.active").removeClass("active");
$(this).addClass("active");
});

If you want the active class on the li - then
if you want to keep the active class on the a - then just change the click handler

$(".nav-item").on("click", function(){
$(".nav-item.active).removeClass("active");
$(this).addClass("active");
});

How to make an active navbar link when it shows its page using react-bootstrap

Import the useLocation hook from React Router then you can make some dynamic classNames:

// ...
import React, { useEffect, useState } from 'react';
// Import useLocation hook
import { Link, useLocation } from 'react-router-dom';

function NavBar() {
const location = useLocation(); // once ready it returns the 'window.location' object
const [url, setUrl] = useState(null);
useEffect(() => {
setUrl(location.pathname);
}, [location]);
// ...
return (
// ... Just a dumbed down example:
<Nav>
<Link to="/" className={"underline" + (url === "/" ?" active" : "")}>Home</Link>
<Link to="/projects" className={"underline" + (url === "/projects" ?" active" : "")}>Projects</Link>
<Link to="/contact" className={"underline" + (url === "/contact" ?" active" : "")}>Contact</Link>
</Nav>
);
}

And so on. Do this for each Link and add the path name, and it'll work like expected.

Obviously in your CSS you need to create a class to show the active link, e.g.:

.active {
color: red;
}

Update

Now with React Router 6's <NavLink> component, you can easily implement this by reading the isActive argument passed to a function inside the className prop:

// ...
import React, { useEffect, useState } from 'react';
// Import useLocation hook
import { NavLink } from 'react-router-dom'; // import the NavLink component

function NavBar() {
// ...
return (
<Nav>
<NavLink to="/" className={({ isActive }) => "underline" + isActive ? " active" : ""}>Home</Link>
<NavLink to="/projects" className={({ isActive }) => "underline" + isActive ? " active" : ""}>Projects</Link>
<NavLink to="/contact" className={({ isActive }) => "underline" + isActive ? " active" : ""}>Contact</Link>
</Nav>
);
}

This makes our works a lot more flexible and not hard-coded.

Changing the active class of a link with the twitter bootstrap css in python/flask

Have you looked at this ? https://jinja.palletsprojects.com/en/3.0.x/tricks/#highlighting-active-menu-items

Highlighting Active Menu Items

Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s possible to define the active menu item in the child template:

{% extends "layout.html" %}
{% set active_page = "index" %}

The layout template can then access active_page. Additionally it makes sense to define a default for that variable:

{% set navigation_bar = [
('/', 'index', 'Index'),
('/downloads/', 'downloads', 'Downloads'),
('/about/', 'about', 'About')
] -%}

{% set active_page = active_page|default('index') -%}
...
<ul id="navigation">
{% for href, id, caption in navigation_bar %}
<li{% if id == active_page %} class="active"{% endif
%}><a href="{{ href|e }}">{{ caption|e }}</a>
</li>
{% endfor %}
</ul>


Related Topics



Leave a reply



Submit