user2266813
user2266813

Reputation: 87

add a css class after click

I would like to be able to add a class addclass when a user clicks the href element. I am using coffeescript. Any advice?

<div class="visual-tabs">
    <ul id="myTab" class="nav nav-tabs event-type">
        <li>
            <a class="form-scores">Test</a>
        </li>
        <li>
            <a class="form-scores">Test 2</a>
        </li>
    </ul>
</div>

This is what I have so far:

$(document).on 'click', "#myTab .nav-tabs li a", (e) ->
  $(this).addClass('selected')                        

Upvotes: 2

Views: 121

Answers (2)

Chris Bier
Chris Bier

Reputation: 14447

The problem is with your selector. By writing the selector the way you have it, you are looking for an element with the class nav-tabs that is a child of an element with the ID of myTab.

So, "#myTab .nav-tabs li a" needs to be#myTab.nav-tabs li a or simplified to ".nav-tabs li a" or "#myTab li a"

The reason why this is happening is because the #myTab CSS selector is targeting the ul thereby causing it to look for an element with the class nav-tabs that is a child of that ul (which is not what you're intending).

That's why combining those two selectors fixes the problem (e.g. #myTab.nav-tabs). Doing that will cause it to look for any element with both of those classes, and then any li that is a child of it.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104785

Remove the .nav-tabs from your selector, it's searching for that as a child of #myTab. It's also a bit redundant, you're already selecting a unique ID.

$(document).on 'click', "#myTab li a", (e) ->

Upvotes: 4

Related Questions