Magnus
Magnus

Reputation: 514

How to stop event propagation on onclick event in html attribute?

I have a html element with an onclick attribute and I need to prevent that event from bubbling up. I tried doing this:

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

and this:

<div onclick="(function(event){event.stopPropagation();})();)">

But neither works. I absolutely need to do this in the html onclick attribute since this div is part of a Razor partial view and the script is set on the ViewData dictionary. How do I call event.stopPropagation() on the html onclick attribute?

Edit: the error in this case is that event is null. So for some reason, I can´t access the event like this.

Upvotes: 3

Views: 9618

Answers (2)

pizzamonster
pizzamonster

Reputation: 1266

The onclick inline function is implemented as:

function(event) {
}

So you can just use the 'event' variable.

<div onclick='event.stopPropagation(); event.preventDefault()'>

There is no need to implement inline functions. Your first example should work if you add the event.preventDefault().

Upvotes: 0

Joseph
Joseph

Reputation: 1041

Use event.stopPropagation method of Event. There is a mistake in your second code snippet where you do not pass event to the anonymous function. Fixed code:

<div onclick="(function(e) { e.preventDefault(); e.stopPropagation(); })(event)">

Upvotes: 4

Related Questions