Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent execution of parent event handler

I have a tree of divs:

<div id="a" onclick="func">     <div id="b" onclick="func">          <div id="c" onclick="func">          </div>     </div> </div> 

When a click is made on a div it makes it's children invisible - ie click on "a" will turn "b" and "c" invisible.

function func{    if ($(childId).hasClass("visible")){     $(childId).removeClass("visible");     $(childId).addClass("invisible"); } 

The problem is: a click on "b" will call "a"'s click and make "b" and "c" invisible. How do I disable the click on "a" using jQuery?

thanks

like image 782
Guy Avatar asked Sep 09 '09 09:09

Guy


People also ask

How do you prevent click event on parent element?

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 you stop event propagation from parent to child?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do I stop parent onClick event in react?

By default when the onClick event of the child element is triggered, the event on the parent element would also get triggered, but the stopPropagation() method prevents this behavior.


2 Answers

You can add a handler for the child that will prevent the click event from propagating up:

function handler(event) {     event.stopPropagation();     // now do your stuff         } $('#a').add('#b').click(handler); 

This way clicks to '#b' will not propagate to '#a'. Neither will clicks to '#c' go to '#b', and hence not to '#a'.

like image 83
jrharshath Avatar answered Sep 20 '22 07:09

jrharshath


use

event.stopPropagation()

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

when click on b and c

like image 32
rahul Avatar answered Sep 20 '22 07:09

rahul