Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel click event of container div trigger when click elements which inside container in JQuery?

Tags:

jquery

events

E.g

<div class="container">
  <div class="inside">I am not fire when click me</div>
</div>

$('.container').click(function(){
  // container do something here
});

but,when I click the div inside it also trigger the container's click event because the div is inside the container, so , I need a way to prevent the container event trigger when I click on the inside div!

Thank you very much!!

like image 578
qinHaiXiang Avatar asked Feb 23 '11 15:02

qinHaiXiang


People also ask

How do I cancel a click event?

You can cancel actions caused by row click events by calling event. stopImmediatePropagation() in an onRowClick event handler. If necessary, you can specify the same code for onCellClick.

How do I prevent a parent's onClick event from firing when a child is clicked?

By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.

How do I stop a click event in HTML?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.


1 Answers

As a more general solution, you should check e.target in container's click event handler.

$('.container').click(function(e) {
   // If you want to ignore clicks to anything inside the `.container` div:
   if (!$(e.target).hasClass('container')) return;
   // or, if you only want the `.inside` div to not fire the event,
   if ($(e.target).hasClass('inside')) return;

   // container do something here
});

This way you're not preventing propagation of the event, which would break bound live handlers.

like image 119
josh3736 Avatar answered Oct 23 '22 11:10

josh3736