Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent javascript onclick on child element

Ok, simple question:

<div onclick="javascript:manualToggle(this)">
    <span>Allowed to click</span>
    <span>Not allowed to click</span>
    <span>Allowed to click</span>
</div>

Without replicating the manualToggle on to the 2 spans that are allowed to click, how can I prevent the "Not allowed to click" span from firing it's parent div onclick event when it is clicked on?

like image 349
Paul Avatar asked Sep 16 '09 09:09

Paul


People also ask

How do you prevent the Click event on a child element?

Use stopPropagation method, see an example: $("#clickable a"). click(function(e) { e. stopPropagation(); });

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

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.

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.


1 Answers

Give the span an id an attach onclick event to it and use

A jQuery sample

$("#spn2").click(function(event){
  event.stopPropagation();  
});

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

like image 65
rahul Avatar answered Oct 12 '22 15:10

rahul