Reputation: 21995
I am working on a legacy web app which I am progressively ajaxifying and have found the need to stop event propagation from an inline onclick
handler.
Take this for example:
<a id="inner" onclick="return handleOnclick();" href="#">Some link</a>
Apart from the onclick
handler, there are listeners added with addEventListener
. I need that under certain conditions the onclick
handler can stop the propagation of the event. I've tried event.stopPropagation()
but it does not seem to work. Here's a jsfiddle to test:
http://jsfiddle.net/APQk6/985/
Any ideas?
Upvotes: 1
Views: 3006
Reputation: 21995
Found a solution based on Felix Kling's comments:
event.stopImmediatePropagation()
instead of event.stopPropagation()
Here's a working solution:
Upvotes: 2
Reputation: 28678
You can use a "cancelled" attribute. Not nice, but works. http://jsfiddle.net/koldev/45zbA/
HTML
<script>
function handleOnclick(self) {
self.setAttribute("cancelled", confirm('Stop event?') ? "1" : "0");
return false;
}
</script>
<div>
<a id="inner" onclick="return handleOnclick(this);" href="#">Some link</a>
</div>
JavaScript
document.getElementById('inner').addEventListener('click', function(e){
if (this.getAttribute("cancelled") == "1") {
return;
}
alert("Listener called");
});
Upvotes: 1