[javascript] How to stop event propagation with inline onclick attribute?

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?

This question is related to javascript html events dom

The answer is


<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>

According to this page, in IE you need:

event.cancelBubble = true


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>

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;
    }
}

According to this page, in IE you need:

event.cancelBubble = true


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;
    }
};

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)"...>

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;"

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;
   }
}

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
}

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)" />

According to this page, in IE you need:

event.cancelBubble = true


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.


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. :)


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;
    }
};

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>

According to this page, in IE you need:

event.cancelBubble = true


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;
   }
}

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;
    }
}

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>

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.


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;
    }
}

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;"

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)" />

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.


<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>

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
}

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;
    }
}

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. :)


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)"...>

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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component