Tutorial :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?


You need an event handler (it's very easy to do this in something like jQuery) that catches clicks for the spans within the div and only fires the function if, for example, the span has/hasn't a particular class.


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.


It would make sense to use a library but without you can try this (edited with an entire page to test):

<html><head></head>  <body>  <script type="text/javascript"><!--  function manualToggle(val)  {      alert(val.id);  }    --></script>    <div id="test" onclick="manualToggle(this);">      <span>Allowed to click</span>      <span onclick="event.cancelBubble=true;if (event.stopPropagation) event.stopPropagation();">Not allowed to click</span>      <span>Allowed to click</span>  </div>  </body>  </html>  


with mootools you can use the method stopPropagation:

$('myChild').addEvent('click', function(ev){      ev.stopPropagation(); // this will prevent the event to bubble up, and fire the parent's click event.  });  

see http://mootools.net/docs/core/Native/Event#Event:stopPropagation

also see this very similar question: How can I stop an onclick event from firing for parent element when child is clicked?


Possible solution: give the span's id's and check whether the clicked id is allowed to be clicked in your function

bad idea: you don't know which span is clicked since you call the function from your div...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »