Tallan Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Overriding jQuery Functions

In my last post I showed how to create a localized instance of jQuery that performed custom selection by handling ID selectors in a specific way. There are other parts of jQuery though that can have IDs passed in for arguments, such as the find and children functions. These functions can also be customized to override the default behavior as well. In this example, if the find and children functions are left unchanged, they will fail find any elements by ID if we don’t include the end part of the ID that we append in the $$ function. So let’s look at overriding / extending the find function.

// Extended .find(selector) to append the _elementId to any
    // ID selector (containing "#")
    (function ($$) {
        var originalFind = $.fn.find;
        $$.fn.find = function (selector) {
            selector = getFullSelectorIds(selector);
            return originalFind.call(this, selector);

In the above code we are using a self-executing function to replace jQuery’s find function (specifically for the $$ instance, not the default instance). In this example we do not want to completely remove the original find function, since we do want to use it, we just need to do some preprocessing of the selector. What we do is store a copy of the original, (in originalFind) and then we replace find with our new one. The new one works just like the $$ function in my previous post, only we just have the one argument to process. Then to actually perform the find, we call the originalFind using the processed selector.
Of course this is just one specific case, but any of the built-in jQuery functions can be overridden in the same way. Likewise this is how one would add completely new functionality to jQuery.

Learn more about Tallan or see us in person at one of our many Events!

Share this post:

No comments

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=""> <s> <strike> <strong>