2
<div onclick="foo()">
    <button onlick="bar()"/>
</div>

If they click the button I want bar() to fire, if they click anywhere else in the div EXCEPT on the button I want foo() to fire. But what happens currently is if I click the button I get both events firing.

thanks

snappymcsnap
  • 2,050
  • 2
  • 29
  • 53
  • Please use preventDefault(); jquery function https://www.w3schools.com/jquery/event_preventdefault.asp#:~:text=preventDefault()%20method%20stops%20the,link%20from%20following%20the%20URL – Visakh R krishnan Jun 09 '20 at 18:25
  • Does this answer your question? [Ignore parent onclick when child onclick is clicked, using Javascript only](https://stackoverflow.com/questions/49689478/ignore-parent-onclick-when-child-onclick-is-clicked-using-javascript-only) Also: https://stackoverflow.com/questions/26061254/ignore-parent-onclick-event-when-child-element-is-clicked and https://stackoverflow.com/questions/33281148/how-to-prevent-parent-click-event-when-the-user-clicks-on-his-child-element-ang First three results from a google search. – Run_Script Jun 09 '20 at 18:26

2 Answers2

4

You should use event.stopPropagation() to stop the bubbling of event to the containing parent div.

function bar(event){
  event.stopPropagation();
  alert('button clicked')
}

function foo(event){
  alert('div clicked')
}
<div onclick="foo()">
    <button onclick="bar(event)"/>
</div>
ABGR
  • 4,631
  • 4
  • 27
  • 49
0

Your problem can solve using stopPropagation() Event Method is javaScript. visit the link https://www.w3schools.com/jsref/event_stoppropagation.asp . Here you will find solution and easy explanation. You recommended to play with example in the website.

Bin Rohan
  • 370
  • 4
  • 13