Override Core jQuery Methods
December 10, 2009A recent conversation with some developers brought up a question I’d never contemplated before: Can jQuery core methods be overridden? Well, in short: Easily, yes!
From perusing the web, it looks like there are several approaches to doing this. Below is an example I wrote up quickly, to test out the concept.
jQuery.fn.extend({
// Override the core hide() method
hide : function() { alert('hide method overriden'); }
});
And now to test it out:
$('#test').click(function() {
$(p).hide();
});
When clicking on a link with an id=test, it will use my overridden method. I know this isn’t a practical example, but does show how overriding jQuery core methods is possible!
Here’s another example (view the source): http://expressionindesign.com/files/jqueryOverride/jquery_override.html
Other References
- A more complete example
- jQuery Documentation Example
If JQuery would have been so nicely object-oriented like MooTools, you could have simply extended the class
@Adrian – There actually is a way to extend a core method but not like how MooTools does it. It’d be great if jQuery got to that point one day!
For anyone looking for a way to overide the “hide” Jquery function, here is how do to it ( you need a return somwhere, otherwise $(somthing).hide().else() will not work)
Bonus, a way to keep the overidden function, and how to still call it !
var originalHideMethod = jQuery.fn.hide;
jQuery.fn.extend({
// Override the core hide() method
hide : function(arguments) { console.log(‘do somthing usefull here’); return originalHideMethod.apply( this, arguments ); }
});
Its called duck punching, heres a good example of doing it in a way that allows the original function to be called based on a conditional: http://paulirish.com/2010/duck-punching-with-jquery/