matt
matt

Reputation: 99

Jquery click - thinks its the parent element, not the child

When I click on a child element inside a div (the 'butMedWhite ' class) - the jquery thinks that I am clicking on the parent element ('.alternative') - even when I dump 'this' inside the console it says i have clicked on the class 'alternative' (see code below) - not the 'butMedWhite ' class - does anyone have any ideas why? Here is the html:

<div class="alternative _activeCategory">
    <div class="alternative_inner"></div>
    <div class="expandable" style="display: block;">
        <div class=" criteriaContainer">
            <a class="butMedWhite altCreator">add rule</a>
        </div>
    </div>
</div>

and here is the jquery:

$('.altExpander').on('click', '.alternative', function(e) {
                    console.log(this);
                    if(!$(this).hasClass('_activeCategory')){
                        expandCategory($(this));
                    }else{
                        closeCategory();
                    }
                });

Thanks for any help!

Upvotes: 2

Views: 664

Answers (2)

tandrewnichols
tandrewnichols

Reputation: 3456

That's because your selector is ".alternative" in this line:

$('.altExpander').on('click', '.alternative', function(e)

If you want this to be the anchor tag, you need to use

$('.altExpander').on('click', '.alternative a', function(e)

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

jQuery provides as context to your callback the element on which you bound the event handler, just like the native DOM functions.

If you want the clicked element instead, don't use this but e.target :

$('.altExpander').on('click', '.alternative', function(e) {
     var clicked = $(e.target);
     console.log(clicked);
     if(!clicked.hasClass('_activeCategory')){
            expandCategory(clicked);
     }else{
            closeCategory();
     }
});

Upvotes: 2

Related Questions