Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending an existing jQuery function

I am trying to write a plugin that will extend an existing function in jQuery, e.g.

(function($) {     $.fn.css = function()     {         // stuff I will be extending         // that doesn't affect/change         // the way .css() works     }; })(jQuery); 

There are only a few bits I need to extend of the .css() function. Mind me for asking, I was thinking about PHP classes since you can className extend existingClass, so I'm asking if it's possible to extend jQuery functions.

like image 661
MacMac Avatar asked Feb 15 '11 17:02

MacMac


People also ask

What is extend function in jQuery?

The jQuery. extend() method is used to merge contents of two or more objects together. The object is merged into the first object. You can try to run the following code to learn how to use extend() method −

How do you extend a function in JavaScript?

Use extendFunction. init = extendFunction(init, function(args) { doSomethingHereToo(); }); But in your specific case, it's easier to extend the global onload function: extendFunction('onload', function(args) { doSomethingHereToo(); });

What is FN extend?

extend() method is used to merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.

What is jQuery object?

A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties: length. context. selector.


1 Answers

Sure... Just save a reference to the existing function, and call it:

(function($) {     // maintain a reference to the existing function     var oldcss = $.fn.css;     // ...before overwriting the jQuery extension point     $.fn.css = function()     {         // original behavior - use function.apply to preserve context         var ret = oldcss.apply(this, arguments);          // stuff I will be extending         // that doesn't affect/change         // the way .css() works          // preserve return value (probably the jQuery object...)         return ret;     }; })(jQuery); 
like image 149
Test Employee 1 Avatar answered Oct 19 '22 00:10

Test Employee 1