Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Magnus Avatar asked Jan 29 '26 15:01

Magnus


1 Answers

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

like image 116
Joseph Avatar answered Jan 31 '26 05:01

Joseph