Cesar Bielich
Cesar Bielich

Reputation: 4945

not selector, on() click event not working

I have my HTML as so

<tr class="show_ticket_preview">
    <td>
         <a class="ticket_preview_id">A Link</a>
         <p>Some other stuf</p>
    </td>
</tr>

I need to trigger the click event when the tr is clicked but not when a <a> is clicked in the tr

$(document).on('click', '.show_ticket_preview:not(.ticket_preview_id)', function() {

but for whatever reason the event is still triggering when I click on ticket_preview_id based on my code above.

Any ideas?

Upvotes: 3

Views: 342

Answers (2)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

.show_ticket_preview:not(.ticket_preview_id) selector will select all elements that has class show_ticket_preview but not has class ticket_preview_id so it's not working in your case.

To solve your problem, you can use event object in the handle then check if the target has class ticket_preview_id or not:

$(document).on('click', '.show_ticket_preview', function(e) {
  if(!e.target.classList.contains("ticket_preview_id")) console.log(1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show_ticket_preview">
    <div>
         <a class="ticket_preview_id">A Link</a>
         <p>Some other stuf</p>
    </div>
</div>

Upvotes: 4

Alex Hodson
Alex Hodson

Reputation: 138

Have another click event which is tied to the ticket_preview_id and make use of the stopPropagation method.

$(document).on('click', '.show_ticket_preview', function() {
    // Do Something
})

$(document).on('click', '.ticket_preview_id', function(e) {
    e.stopPropagation()
})

You can see more about stopPropagation here... https://api.jquery.com/event.stopPropagation/

Upvotes: 2

Related Questions