0

I have a table with some data inside. When I click on a element, it adds a class .active to :

 $('#someId').on('click', 'tr', function (e) { var target = $(this).find(".target"); var prev = target.html(); timeCell.html(target.data('prev')); timeCell.data('prev', prev); if ($(this).hasClass('active')) { $(this).removeClass('active'); } else { $(this).addClass('active'); } }); 

As you can see after clicking on tr, users could see some icons instead of previous data (.target) and I want them to click on icons ("prev") that call some other functions. But when the icons are clicked, a click on a parent element is execute too. How can I avoid this?

---- If anybody needs help in this case - here's the solution!

 $('#someId').on('click', 'tr', function (e) { var senderName = e.target.tagName.toLowerCase(); if (senderName === 'div') { //do some staff } else { var target = $(this).find(".target"); var prev = target.html(); timeCell.html(target.data('prev')); timeCell.data('prev', prev); if ($(this).hasClass('active')) { $(this).removeClass('active'); } else { $(this).addClass('active'); } }); 
1
  • In that case, simply use e.stopPropagation() will stop the click event from bubbling up to the parent <tr> element ;) Commented Jun 11, 2017 at 14:16

1 Answer 1

3

The reason why the click event on the parent <tr> element is being fired is due to event bubbling. You can stop the click event emitted within the child node from bubbling up (and being captured by the click event listener bound to the parent), is to simply call event.stopPropagation() in the child click event, i.e.:

$('#someId').on('click', 'tr', function (e) { // Stop click event from bubbling up to parent and getting captured e.stopPropagation(); // Rest of the logic var target = $(this).find(".target"); var prev = target.html(); timeCell.html(target.data('prev')); timeCell.data('prev', prev); if ($(this).hasClass('active')) { $(this).removeClass('active'); } else { $(this).addClass('active'); } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

I saw this method in suggested post, while been writing a question. It didn't solve my problem. Don't know why..
What is the other click handler on the <tr> element?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.