Grodriguez
Grodriguez

Reputation: 21995

Stopping event propagation from an onclick handler

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

Answers (2)

Grodriguez
Grodriguez

Reputation: 21995

Found a solution based on Felix Kling's comments:

  • Need to call event.stopImmediatePropagation() instead of event.stopPropagation()
  • Need to pass the actual event object from the inline handler (this question was also useful)

Here's a working solution:

http://jsfiddle.net/r95cC/3/

Upvotes: 2

kol
kol

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

Related Questions