Question

Is there a way to run a function only if event.preventDefault() is called on an event (by another unknown function). This is for a jQuery plugin, so I don't have any knowledge of what other parts of the page might be doing. I've tried this:

Event.test = Event.preventDefault;
Event.preventDefault = function () {
    alert('Success');
    this.test();
}

but it doesn't work... just behaves as normal, with no errors.

Conversely, I want the opposite too... to call a function only if event.preventDefault() isn't called. In effect, to add a function to the default action for an event. Any ideas? Is all this at all possible?

Edit: Based on the comment, I've got a solution to the first problem: http://jsfiddle.net/nathan/VAePB/9/. It works in Chrome (alerts function preventDefault() { [native code] }, but IE alerts undefined. So IE won't let me define Event.prototype.test, but it will let me redefine Event.prototype.preventDefault. Weird. I'm sure I can come up with a solution to the the second problem based on this one if I can just get it to work in IE.

Was it helpful?

Solution

For the first problem, try something like this:

oldPreventDefault = Event.prototype.preventDefault;
Event.prototype.preventDefault = function() {
    //do stuff
    oldPreventDefault.call(this);
}

I don't know if that will work, but it might be worth a shot.

For the second problem, I would try something similar to live event handling. Put a listener on a parent element (i.e. body or a top-level div). If you can get your hook into preventDefault as noted before, you can use that to set a flag. If the event bubbles up to that element and your flag isn't set, do your extended behavior. Though this won't work with all events, since not all events bubble. Another way to tackle this problem might be to delay execution until the current stack has finished using setTimeout(0,...) and then checking the flag.

OTHER TIPS

I'm not sure I've understand. Can't you just use event.isDefaultPrevented() like this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top