Override Core jQuery Methods

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

Comments: 4

  1. adrian says:

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

  2. Rick says:

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

  3. Guile says:

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

  4. Steve says:

    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/

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>