Search code examples
javascripthtmlevent-handlingonclickevent-bubbling

Knowing if a previous handler for an event returned false. defaultPrevented in IE < 9?


I've put a global modal "Loading, please wait" <div> in an application. It is showing every time an <a> or <input type="button"> is clicked. This is achieved by assigning the <body> an onclick event handler in onload, so that it gets executed when the event bubbles up:

<body onload="setup()">
    <!-- No control over what will be here -->
</body>

<script>
function setup() {
    document.getElementsByTagName('body')[0].onclick = clickFunc;
}
function clickFunc(eventData) {
    var clickedElement = (window.event) ? event.srcElement : eventData.target;
    if (someConditions) { 
        document.getElementById('modal').style.display = "block";
    }
}
</script>

Now, I've got some components in the markup (over which I have no control) that do return false in their onclicks. That's causing the modal popup to show and just stay there when there's a confirm() and the user denies. Probably the proper way of dealing with this would have been preventDefault(), so that the event wouldn't bubble up, as explained in event.preventDefault() vs. return false.

But I don't have control over that part, so: Is there a way (preferrably non-jquery+cross-browser) to know the result of previous executions of the event handler (at lower levels) ?

If there isn't I guess I'll just have to refrain from showing the modal <div> whenever the component's onclick contains return false.

Here is a JSFiddle for testing.

UPDATE

Bergi's answer below is what I was searching for. However, defaultPrevented doesn't seem to be supported in IE < 9. Is there an equivalent/workaround to achieve that in IE < 9?


Solution

  • You could check for (window.event ? event.defaultPrevented : eventData.isDefaultPrevented()) == false to catch propagated events that have not returned false.