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

Javascript help.

I need some help with my javascript code. I'm trying to get my javascript to change the class of my navigation links to "active" once clicked. I already have some CSS set up for the class of "active" which works fine if I put it in my HTML.

But for some reason, when I click on the links the css doesn't work as it should. And slo the link which starts off as "active" doesn't have the class removed.

I was thinking it might be where I've placed my script tags? They're currently in my Head tags, below my CSS links?

Sorry I should of added my code.

$(document).ready(function () {
     $('.nav_links li a').click(function(e) {
     $('.nav_links li').removeClass("active");
     var $parent = $(this).parent();
     if (!$parent.hasClass('active')) {     
         $parent.addClass('active');            
     }
     e.preventDefault();
});
.active {
    border-bottom: 4px solid $primary-color;
    color: $primary-color;
}

2 Answers

Usually you want to move the preventDefault method to the top of your event handler. Also in the code you posted you haven't closed the $(document).ready() method. I tested your code with the preventDefault method where you had it, with the properly closed $(document).ready() method and it worked just fine. :)

$('.nav_links li a').click(function(e) {

   $('.nav_links li').removeClass("active");

   var $parent = $(this).parent();

   if (!$parent.hasClass('active')) {
       $parent.addClass('active');
   }

   e.preventDefault();
});

Thanks Peter. But it's still not working for me?

My "Home" link which is marked as "Active" in the HTML stays active. That link is styled correctly but the other links, when clicked don't have the same styling while the home stays the same.

Fixed it now. I realised it was changing the class of the li tag rather than the a tag.