- Source:
Methods
-
<static> jQuery.fn.preempt(options, callback) → {jQuery}
-
Takes legacy inline JS (i.e.
onclick
andhref="javascript:..."
) and creates event handler(s) to be run around the inlined code.This:
- jQuery
Parameters:
Name Type Argument Description options
Object attr
is the attribute you want to replaceevent
is the new event to bindbefore
is a function you wish to execute before the inline handler. The second parameter,callback
, will be overridden by this function. If this function returnsfalse
or halts immediate propagation, the inline function will not be called, and further immediate propagation of the event will not occur.after
is a function you wish to execute after the inline handler. If this function returnsfalse
or halts immediate propagation, further immediate propagation of the event will not occur.forcePropagation
causes yourafter
function to be executed regardless of whether the inline function stopped immediate propagation or returnedfalse
. In this case, if the inline function happened to returnfalse,
the default action for the event (whatever that may be; see http://api.jquery.com/event.preventDefault/) will be prevented and bubbling will not occur. Ifafter
is not present, this does nothing.data
is an object with keysbefore
, andafter
. The values will be passed, respectively, to thebefore
andafter
functions as the second parameter (the first will be the Event itself). A third key,js
, is automatically added to the objects, and its value is the original contents of theattr
attribute. It will have thejavascript:
prefix stripped, if present. It's worth remembering that the context (thethis
) of an inline function is the DOM element itself.
callback
function <optional>
Event handler callback function to be executed before the inline handler. Alias for
options.before
; if both are present thenoptions.before
will take precedence.- Source:
- To Do:
-
- Document more thoroughly.
- support for delegate-style usage
Returns:
A jQuery obj
- Type
- jQuery
Example
// given <button onclick="doSomething()">do something</button> // or <a href="javascript:doSomethingElse()">do something else</a> // Basic usage: $('button').preempt({ attr: 'onclick', event: 'click', }, function doSomethingBeforeSomething() { // do something else }); // Restoring the inline JS: $('button').preempt({ attr: 'onclick', event: 'click', restore: true }); // Fancy usage: $('button').preempt({ attr: 'onclick', event: 'click', before: function executedBeforeInlineJS(event, data) { // stuff; return false to halt propagation to inline JS }, after: function exectedAfterInlineJS(event, data) { // things; return false to prevent the default action and stop propagation }, // will execute the after() function even if the inlined JS returned false. forcePropagation: true, data: { before: 'some data to be passed to the before() function', after: 'some data to be passed to the after() function', } });