Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a jQuery plugin

Tags:

jquery

Has anyone extended an existing jQuery plugin?

I am unsure of where to start. I would rather not actually copy and modify the plugin I wish to extend. Do I do this through prototype or just an extend call on the plugin in question?

Or am I dreaming that it would make sense to do this?

like image 460
Chad Ruppert Avatar asked Apr 16 '09 18:04

Chad Ruppert


People also ask

Which will extend jQuery?

The jQuery. extend() method is used to merge contents of two or more objects together. The object is merged into the first object.

What is FN in jQuery?

fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn.

Where can I download jQuery plugins?

There are plenty of jQuery plug-in available which you can download from repository link at https://jquery.com/plugins.

How do I save a jQuery file?

Find the jQuery library js file download link, right-click it, in the popup menu list click Save Link As menu. The above action will save the jQuery library js file in a local folder, you can save it to any folder( for example your project lib folder).


2 Answers

EDIT: As pointed out by Seb, this is not strictly an example of 'extending' a plugin, more 'encapsulating' a plugin, so take it as it comes :)

Here's something I did to simplify my usage of the jquery autocomplete plugin a while ago:

// small autocomplete plugin wrapping the full autocomplete plugin for a standard look and feel
(function($) {
    $.fn.standardAutocomplete = function(type) {
        return this.autocomplete(ToAbsoluteUrl("~/System/Autocomplete/" + type), {
            formatItem: formatItem,
            formatResult: formatResult
        });
        // Autocomplete formatting callbacks
        function formatItem(row) { return row[0] + "<span class=\"sub\">" + row[1] + "</span>"; }
        function formatResult(row) { return row[0].replace(/(<.+?>)/gi, ''); }
    }
})(jQuery);

Now that's not following "by the book" jquery coding practise - e.g. I'm not accounting for the fact there could be multiple elements selected, but in this case, I know I'm never going to select more than one element on a page with this so I wanted to keep simple, and it "works for me". You might be able to use a similar approach, perhaps with a little more sophistication.

like image 86
Steve Willcock Avatar answered Nov 07 '22 20:11

Steve Willcock


If the plugin is well done, then you don't have many alternatives other than using its options to change its behavior.

The purpose of this is that all its code is encapsulated and doesn't interfere with other code, so you can't inject any code in it.

If you really need to change its behavior, then I guess you'll need to copy & paste the code.

like image 32
Seb Avatar answered Nov 07 '22 21:11

Seb