Make Twitter Bootstrap navbar link active
Asked Answered
M

10

39

What's the standard way to make the active link in a Twitter Bootstrap navbar bolded? It's clear that a link gains the active appearance by gaining the "active" class. For example, the Home link below is active. When I click any link in the navbar, should a use jQuery to remove all classes from li elements and then add the active class to the link I've id'd?

<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>

EDIT: I included

<script type="text/javascript">
$('.nav li a').on('click', function() {
    alert('clicked');
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active');
});
</script>

after the links. The alert appears when I click a link, but the "active" class is not added to the link.

Here's all of my navbar HTML:

<div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="brand" href="#">AuctionBase</a>
            <div class="nav-collapse">
                    <ul class="nav">
                        <li><a href="home.php">Search</a></li>
                        <li><a href="about.php">About</a></li>
                    </ul>
            </div>
        </div>
    </div>
</div>
Madalinemadalyn answered 5/8, 2012 at 2:21 Comment(0)
G
43

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"';
}

?>
Guarani answered 5/8, 2012 at 5:47 Comment(3)
Thanks for the hint. I just put the if right in line (Rails code): <% if current_page?(controller: 'about') %><li class="active"><% else %><li><% end %><%= link_to "About", about_path %></li> I used an else just to make it more readable.Attenborough
Instead of using $_SERVER['REQUEST_URI'] you could use $_SERVER['PHP_SELF'] - that way you support uri's with parameters.Gintz
Very nice way of doing this, I've been torn between switch statements for different states, and each li element having an if statement similar to the function. Definitely deserving of up votesExtremity
A
29

http://totalprogus.blogspot.sk/2013/12/bootstrap-add-active-class-to-li.html

This tutorial has a great and ultimate solution for this "problem". I was dealing with it a while ago and working great for me, customizable as well

$(document).ready(function() {
    $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
});
Animalism answered 1/8, 2014 at 14:49 Comment(1)
This is the cleanest solution I've found. The only thing I'd add is the id of your navbar before the <a> in the selector. It just gives jquery less to search through e.g. $('#main-navbar .nav a[href="' + this.location.pathname + '"]').parent().addClass('active');Granitite
T
10

If you do not want to deal with server side and in the case where all hrefs are simple, like '/page.php', you can call

$('.your-nav-container').find('a[href="' + location.pathname + '"]').parents('li').addClass('active');

after page is loaded.

Trachytic answered 24/4, 2014 at 16:31 Comment(2)
This is the only correct answer that exclusively uses Bootstrap and JQuery. It also works with dropdown nav elements. The trick appears to be .parents('li').Oogonium
Actually, .parents('li') will mark every li containg the link with the active class. I would recommend .closest('li') which will find the first parent that is an li.Dagan
I
9

You can try:

$('.nav li a').on('click', function() {
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active').css('font-weight', 'bold');
});

It would be best to give your nav an id attribute though, because you may have more than one nav on a page with the nav class.

$('#main-nav li a').on('click', function() {
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active').css('font-weight', 'bold');
});

Alternatively, instead of using .css('font-weight', 'bold'), you could just put this in the stylesheet:

.active {
    font-weight: bold;
}
Iinden answered 5/8, 2012 at 2:27 Comment(4)
Like mentioned by Chris Moutray before, this script would only update the class and then reload the page, which makes the change become lost.Munger
@Josephjun.Melettukunnel I assume his point in wanting to do it with jQuery is that he's not reloading the page. Otherwise, he wouldn't want to do it with jQuery - just change the active nav item in HTML or using PHP. Looks like he probably wants to load content via AJAX or using the nav items as tabs.Iinden
Her* she* - sorry about that!Iinden
Assuming you reload the whole page, any thoughts on performance of turning on the right navbar selection in the server (php in the above example). Doing it in the client, I think there might be a very small but sometimes noticeable delay between when the page is rendered in the browser and when the navbar link is turned "active"...Torrance
T
3

Add the following script at the bottom of the page:

<script>
    $(document).ready(function() {
        var url = this.location.pathname;
        var filename = url.substring(url.lastIndexOf('/')+1);
        $('a[href="' + filename + '"]').parent().addClass('active');
    });
</script>
Tripper answered 14/2, 2016 at 8:36 Comment(0)
U
2

Chris Moutray your answer helped me a lot in the develop of my software (i'm using ZendFramework). I wrote this view helper:

<?php

class Zend_View_Helper_ActiveOrNot {

    function activeOrNot ( $requestUri ) { 

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

        if ($current_file_name == $requestUri)

            echo 'class="active"';

    }   

}

In this case i call this helper in the view thus:

<?php $this -> activeOrNot ( "public" );

Thanks U!!

Utilitarianism answered 3/3, 2013 at 8:7 Comment(0)
S
1

You can solve it with CSS.

Add a class to the body of each page:

<body class="home">

Or if you're on the contact page:

<body class="contact">

Then take this into consideration when you're creating your styles:

ul li:hover, body.home a.home, body.contact a.contact { background-color: #000; } 
ul li:hover a, body.home li.home a, body.contact li.contact a { color: #fff; }

Lastly, apply class names to your list items:

<ul>
  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>
</ul>

This point, whenever you're on the body.home page, your li.home a link will have default styling indicating it is the current page.

Shoddy answered 17/4, 2015 at 9:45 Comment(0)
C
0

If you assign $pageTitle to the page name, you can do this without javascript

<ul class="nav navbar-nav">

      <li <?php if ($pageTitle == "Website Development") {echo 'class="active"';} ?>>
      <a href="website-development.php">
       Web Development
      </a>
      </li>...</ul>
Collado answered 1/12, 2014 at 9:51 Comment(0)
S
0

Just put the below code into "head" section.

<script type="text/javascript">
$(document).ready(function () {
$("li a[href='" + location.href.substring(location.href.lastIndexOf("/") + 1, 255) + "']").addClass("active");
});
</script>

obviously don't forget your call to jquery.js before.

And your:

<style>
.active{something...}
</style>
Sunderland answered 15/6, 2015 at 10:10 Comment(0)
A
0

You can use this...

<?php 
// Nav Active Links Start //
//echo basename($_SERVER["SCRIPT_FILENAME"], '.php'); 

$baseurl = basename($_SERVER["SCRIPT_FILENAME"], '.php'); 

//if ($baseurl == 'best'){ echo 'active';}
// Nav Active Links End //
?>

<a href="<?php echo $host;?>/en/dashboard/page/1" class="nav-item nav-link <?php if ($baseurl == 'index'){ echo 'active';}?>">Dashboard</a>
<a href="<?php echo $host;?>/b/best/page/1" class="nav-item nav-link <?php if ($baseurl == 'best'){ echo 'active';}?>">Best</a>

Use this latest code updated here: https://www.arnlweb.com/forums/web-development/how-to-make-twitter-bootstrap-navbar-link-active-in-php/

Airtoair answered 14/6, 2022 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.