379

Consider the following:

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>

How can I make it so that when the user clicks the span, it does not fire the div's click event?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Sam
  • 6,167
  • 6
  • 26
  • 24

16 Answers16

361

Use event.stopPropagation().

<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>

For IE: window.event.cancelBubble = true

<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
Munim Munna
  • 17,178
  • 6
  • 29
  • 58
James
  • 109,676
  • 31
  • 162
  • 175
  • 12
    There's no such thing as the event object in FireFox. – Robert C. Barth Dec 23 '08 at 00:07
  • 6
    The event object is a parameter of the callback. Actually, there is no such thing as the event object in IE because this object is accessible through window.event instead of being a parameter of the function :-) – Vincent Robert Dec 23 '08 at 00:22
  • 72
    This is just wrong - inline onclick handlers don't get the event passed as an argument. Correct solution is Gareths, below. – Benubird Dec 09 '10 at 16:22
  • 2
    In Firefox, you can have access to a variable event in inline script, but window.event is not available.
    – Morgan Cheng May 19 '11 at 08:37
  • 1
    ```event``` seems to be available in inline events in IOS Safari as well. – Yuval A. Feb 02 '15 at 23:24
  • Maybe you confused with [the function provided by jQuery](https://api.jquery.com/event.stoppropagation/)? – Niki Romagnoli Dec 01 '16 at 08:53
  • it seems, you muse use `event.stopPropagation()`. if you change `event` to any other parameter name, such as `e`, it can not work. Does anyone known why? – Leon Jul 03 '19 at 13:39
  • Default behaviours, such as clicks on links are not prevented by Event.stopPropagation(). *Source*: [MDN Event.stopPropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) – Dave F Apr 04 '21 at 13:47
223

There are two ways to get the event object from inside a function:

  1. The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  2. The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

Gareth
  • 133,157
  • 36
  • 148
  • 157
86

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you can do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}
Community
  • 1
  • 1
Robert C. Barth
  • 22,687
  • 6
  • 45
  • 52
47

Use this function, it will test for the existence of the correct method.

function disabledEventPropagation(event)
{
   if (event.stopPropagation){
       event.stopPropagation();
   }
   else if(window.event){
      window.event.cancelBubble=true;
   }
}
richo
  • 8,717
  • 3
  • 29
  • 47
SoftwareARM
  • 1,115
  • 10
  • 5
22

I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)

onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
mathieu
  • 30,974
  • 4
  • 64
  • 90
MSC
  • 229
  • 2
  • 2
14

This worked for me

<script>
function cancelBubble(e) {
 var evt = e ? e:window.event;
 if (evt.stopPropagation)    evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>

<div onclick="alert('Click!')">
  <div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
Matias Contreras
  • 442
  • 5
  • 10
  • Are you sure that this exact code snippet worked for you? Because it looks like there is a string quoting issue in the onclick handler of the outer div... ?! – Nicole Nov 21 '18 at 11:51
10

For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.

<div onclick="event.stopPropagation();" ...

or, pass event as a parameter to inner function:

<div onclick="someFunction(event);" ...

and in someFunction:

function someFunction(event){
    event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
    // other onclick logic
}
Evgeny Gorb
  • 1,442
  • 2
  • 13
  • 24
10

I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:

<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>

I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)

user3611941
  • 156
  • 1
  • 3
7

According to this page, in IE you need:

event.cancelBubble = true

ajh1138
  • 566
  • 3
  • 10
6

Use separate handler, say:

function myOnClickHandler(th){
//say let t=$(th)
}

and in html do this:

<...onclick="myOnClickHandler(this); event.stopPropagation();"...>

Or even :

function myOnClickHandler(e){
  e.stopPropagation();
}

for:

<...onclick="myOnClickHandler(event)"...>
CodeToLife
  • 3,672
  • 2
  • 41
  • 29
3

Why not just check which element was clicked? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.

If the target and element aren't equal, it was an event that propagated up.

function myfunc(el){
  if (window.event.target === el){
      // perform action
  }
}
<div onclick="myfunc(this)" />
cs01
  • 5,287
  • 1
  • 29
  • 28
  • Thanks mate, this seems to be the cleanest solution here. On a side-note you have to consider though, that this only matches when the element clicked is the actual topmost element. – Simon Mattes Apr 25 '17 at 21:14
1

This also works - In the link HTML use onclick with return like this :

<a href="mypage.html" onclick="return confirmClick();">Delete</a>

And then the comfirmClick() function should be like:

function confirmClick() {
    if(confirm("Do you really want to delete this task?")) {
        return true;
    } else {
        return false;
    }
};
Rajendra
  • 45
  • 2
  • 2
    This is not what the question meant. – jzonthemtn Sep 26 '13 at 16:53
  • @jbird That's exactly what the question meant. It is a different (older) way to cancel an event from bubbling up the dom tree (it's in the dom api level 1 specs). – gion_13 Oct 02 '13 at 11:29
  • @gion_13 But the click's action isn't something that the user needs to confirm. In the question, we only want the child's onclick() to fire and not the parent's onclick(). Putting a user prompt in between those is not helpful. I hope you can see this difference. – jzonthemtn Oct 03 '13 at 12:13
  • 1
    The `confirm` isn't relevant. I am referring to the **return value**. quote: *In the link HTML use onclick **with return like this*** – gion_13 Oct 03 '13 at 14:51
  • returning false cancels following the link, it doesnt cancel the propagation on my chrome – commonpike Jan 03 '16 at 22:03
1
<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header'); event.stopPropagation()">
    something inside the header
  </span>
</div>
commonpike
  • 10,499
  • 4
  • 65
  • 58
1
Event.preventDefault()

is the current norm, and the one thing that worked for me. See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

    <button value=login onclick="login(event)">login</button>

//and in a script tag
function login(ev){
    ev.preventDefault()
    
    return false;
}

this worked in the latest Chrome, Opera, and IE. (the Mozilla page indicates Firefox would do it too, so I don't even test it!)

Lodewijk
  • 3,741
  • 2
  • 18
  • 15
1

Script

function handleTeste(e) {
  const event = e || window.event;

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

  console.log("Clicked");
}

Html

<div class="favorite" onclick="handleTeste(event)">
  <i class="fa-duotone fa-heart fs-2 text-hover-gray-800 text-primary"></i>
</div>
Caio Agiani
  • 41
  • 1
  • 2
0

The best solution would be handle with the event through a javascript function, but in order to use a simple and quick solution using the html element directly, and once that the "event" and "window.event" are deprecated and not universally supported (https://developer.mozilla.org/en-US/docs/Web/API/Window/event), I suggest the following "hard code":

<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>
jose.serapicos
  • 580
  • 5
  • 10