Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jQuery addClass && removeClass

Hello all, I am building a site with Bootstrap and jQuery. I am trying to make the nav li's change class. I tried looking it up and it gave me the code that i already had.

This is my HTML

        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="index.php">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="menu.html">Menu</a></li>
            <li><a href="contact.php">Contact</a></li>
            <li><a href="gallery.html">Gallery</a></li>
          </ul>
        </div>

This is my jQuery

$(document).ready(function(){ $("nav div ul li").click(function(){ $("li").removeClass("active"); $(this).addClass("active"); }); });

So my problem is when i click on the navigation bar it flicker to active but it always defaults back to Home. If i double click it actually stays which makes me think my code is right?

I am using NetBeans with MAMP since it has some PHP pages. (not sure if it matters)

If anyone could help i would really appreciate it!

Thank you!!

1 Answer

Clicking the links will not only call your .click() handler but will also load the next page. Any changes to the li's class will be erased once the new page is loaded and rendered. It's important to remember that any changes make to the page will only live as long as the page does in the browser. These changes don't persist if you go to a new page or even reload the current page. The page will always start fresh as the HTML defines it.

Makes total sense! I just gave it a class of active on each page. Works now, thanks for the quick response!