-1

I have a page with div and a button on it. I have added onClick event to both of them. Now when I click the button on the div the onClick of the div is also being executed. Is there any way that I can avoid this?

Thank You,

Fox
  • 9,384
  • 13
  • 42
  • 63
  • fix it! Do you think we could see some code to help you? You basically have said "I have a problem" so far. – jeschafe Jul 23 '12 at 15:55
  • 1
    Sounds like a problem with **event propagation**. – Scotty Jul 23 '12 at 15:56
  • possible duplicate of [Prevent click from child firing parent click event](http://stackoverflow.com/questions/6929198/prevent-click-from-child-firing-parent-click-event) – Felix Kling Jul 23 '12 at 15:59

5 Answers5

2

Try this, pass the event as parameter to your onclick event and call

event.stopPropagation();
event.preventDefault();

Your onclick event assignment should be:

$(button).click(function(event) {
    // script here
    event.stopPropagation();
    event.preventDefault();
});
jay c.
  • 1,521
  • 10
  • 9
1

In your click handler you might want to use "stopPropagation" for example:

$("button").click(function(e) {
    // handle this event
    // ...

    // don't pass this event up to parent handlers
    e.stopPropagation();

} );

There's also a related function that you might want to read about called "preventDefault" which tells the browser not to do what it normally does automatically (e.g. submit a page when a submit button is clicked)

See also: https://developer.mozilla.org/en/DOM/event.stopPropagation http://api.jquery.com/event.stopPropagation/ What's the effect of adding 'return false' to a click event listener? http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

Community
  • 1
  • 1
jacobq
  • 11,209
  • 4
  • 40
  • 71
0

in the listener for the link element, you can put e.stopPropagation(), which should fix it (if you're using event bubbling).

If you aren't using jQuery, make sure you set the useCapture parameter of addEventListener() to False info - MDN; you want to be sure you know which direction your events are moving through the DOM (you want them to bubble).

bokonic
  • 1,751
  • 10
  • 12
0

You need to prevent the button onClick event from bubbling to the Div. So basically at the end of your onClick function for the button, once you have done all you logic, you need to call event.stopPropagation()

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

If none of the above work, try out:

$("button").click(function(e) {
    e.stopImmediatePropagation();
});
Tunaki
  • 132,869
  • 46
  • 340
  • 423