Override Core jQuery Methods

Posted on 10. Dec, 2009 by Rick in Blog

A 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

Tags: ,

3 Comments

adrian

03. Mar, 2010

If JQuery would have been so nicely object-oriented like MooTools, you could have simply extended the class

Rick

03. Mar, 2010

@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!

Guile

14. Apr, 2010

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 ); }
});

Leave a reply