45

On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the background colors and everything, however, I changed my CSS to be similar but when I scroll down or click on the menu item the active class does not switch. Not sure what I'm doing wrong.

HTML:

<ul class="menu">
    <li><a href="#" aria-current="page">Home</a></li>
    <li><a href="#about">About Us</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

CSS:

.menu {
  list-style:none;
}
.menu > li {
  float: left;
}
.menu > li > a {
  color: #555;
  float: none;
  padding: 10px 16px 11px;
  display: block;
}
.menu > li > a:hover {
  color: #F95700;
}
.menu a[aria-current="page"],
.menu a[aria-current="page"]:hover {
  color:#F95700;
}

I checked the files; jQuery, bootstrap.js and bootstrap.css are all linked properly. Do I have to add some additional jQuery in or am I missing some CSS to get the active to switch like the subnav menu on their site?

Pepijn Gieles
  • 619
  • 14
  • 23
user1029779
  • 475
  • 1
  • 5
  • 7

13 Answers13

50

This is what I ended up with since you have to clear the others as well.

$('.navbar li').click(function(e) {
    $('.navbar li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});
Jeromy French
  • 11,812
  • 19
  • 76
  • 129
David
  • 501
  • 3
  • 2
  • 1
    would you please post the whole context? which is navbar, which is li? and where is this block of javascript placed? sorry but javascripts are really difficult to understand for me – Zennichimaro Aug 11 '13 at 00:58
  • If the default navbar sets `Home` to `active`, how would you go about maintaining the new `li` as active when the link is clicked and the new page is being loaded,i.e without `preventDefault()`. – Wold Mar 17 '14 at 01:17
  • 3
    @David My issue is this. I see the class `active` being applied to the `li`s after clicked but the link does not change. But, if I remove `e.preventDefault();` when I click it apply the `active` to the `li` but in a second the `active` class move to the default, in this case, the `
  • Home
  • . Any idea? Thanks. – Labanino Oct 03 '15 at 19:18
  • ¡Man!, your are awesome :D – Juan Herrera Feb 09 '16 at 16:44