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

How to add class and removing class with if statement?

Sorry, I am still in the beginning stages of understanding jquery and JavaScript. I am having trouble with this jquery. Am I even on the right track with this?

Here is a CodePen so you can see what I mean: http://codepen.io/anon/pen/oAcGj

I give an example of what I want the one clicked on to look like.

Thanks for any help!

3 Answers

You were on the right track, but needed to do a few things.

Add the click event to the individual <h2> tags instead of the containing <div>. Once you have the click events on the <h2> then you can reference $(this) throughout your code. The rest was pretty good. On the right track.

$('#page_headings h2').on('click', function(){
    if($(this).hasClass('no_highlight')){
        $(this).removeClass('no_highlight').addClass('red_highlight');
    }else{
        $(this).addClass('no_highlight');
    }
});  

I checked your Pen. Make you have jQuery loaded -- In the Settings (gear icon) of the JS panel select JQuery from the 'latest version of' dropdown.

To save some code from your original as well as Miguel Castro's response, you could use toggleClass().

$('#page_headings').on('click', function(){
    $('#page_headings h2').toggleClass( 'red_highlight', 'no_highlight');
});  

A caveat with this:

  • Because of Specificity you NEED to have the red_highlight class to be after no_highlight in the CSS file. So a good rule of thumb is to have the default classes listed before the accessory or enhancement classes in the CSS.

Hi Chase,

You can reduce the code needed with .toggleClass and separating class names with a space.

$('#page_headings h2').on('click', function(){
    $(this).toggleClass('no_highlight red_highlight');
}); 

Each time you click it, it will simply keep switching between "no_highlight" and "red_highlight"

Also, not sure if it matters to you but applying the bottom border shifts everything below that down by 1px. Everything keeps moving up and down 1px each time you click.

You can either use text-decoration: underline to avoid this or give your "no_highlight" class a transparent bottom border so that it's taking up space but you can't see it. border-bottom: 1px solid transparent;