This question is for the purposes of developing jQuery plugins and other self-contained JavaScript snippets that don't require modifying other script files for compatibility.
We all know that event.preventDefault() will prevent the default event so we can run a custom function. But what if we want to simply delay the default event before invoking it? I've seen various, case-specific ninja tricks and workarounds to re-invoke the default action, but like I said, my interest is in a universal way to re-trigger the default, and not deal with default triggers on a case-by-case basis.
$(submitButton).click(function (e) {
e.preventDefault();
// Do custom code here.
e.invokeDefault(); // Imaginary... :(
});
Even for something as simple as form submission, there seems to be no universal answer. The $(selector).closest("form").submit()
workaround assumes that the default action is a standard form submission, and not something wacky like a __doPostBack()
function in ASP.NET. To the end of invoking ASP.NET callbacks, this is the closest I've come to a universal, set-it-and-forget-it solution:
$(submitButton).click(function (e) {
e.preventDefault();
// Do custom code here.
var javascriptCommand = e.currentTarget.attributes.href.nodeValue;
evalLinkJs(javascriptCommand);
});
function evalLinkJs(link) {
// Eat it, Crockford. :)
eval(link.replace(/^javascript:/g, ""));
}
I suppose I could start writing special cases to handle normal links with a window.location
redirect, but then we're opening a whole new can of worms--piling on more and more cases for default event invocation creates more problems than solutions.
So how about it? Who has the magic bullet that I've been searching for?