Skip to content
Advertisement

Cross-browser way to determine whether a DOM event was cancelled

Is there a cross-browser way from a Javascript event handler to determine whether the event has been cancelled by a previous handler? IE and other browsers like Chrome etc. have an event.returnValue property that can be tested, but FireFox doesn’t appear to have any such property.

Here’s an example of the scenario I’m talking about. You have a form like so:

<form id="test" name="test" onsubmit="return false;" />

And you hook up an event to it in Javascript, with addEventListener/attachEvent (hookup omitted for brevity). The event needs to know if anything prior in the chain returned false or otherwise cancelled it. The IE version is like so:

function onSubmitHandler(e) {
    alert("event was cancelled prior to this handler: " + e.returnValue);
}

This works in IE, Chrome, etc., but of course not in FireFox as it doesn’t have event.returnValue. I’ve combed the interwebs for any other way to determine this in FireFox and come up with nothing. Is there a solution for this problem that doesn’t involve setting the onsubmit attribute of the form directly?

Advertisement

Answer

Here’s the kludge way around this. I was hoping for a clean standards compliant method, but it appears there is none.

function onSubmitHandler()
{
    // only called if the other onsubmit handlers succeed
}

// hook in submit
var originalOnSubmit = form.onsubmit;

form.onsubmit = function(e)
{
    var ret;

    if (originalOnSubmit)
        ret = originalOnSubmit();

    if (ret != false)
    {
        return onSubmitHandler(e);
    }
};
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement