41

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.

MacMac
  • 34,294
  • 55
  • 151
  • 222

2 Answers2

82

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);
Sklivvz
  • 30,601
  • 24
  • 116
  • 172
Test Employee 1
  • 942
  • 7
  • 6
0

Same way but a little different than the best answer of this question:

// Maintain a reference to the existing function
const oldShow = jQuery.fn.show

jQuery.fn.show = function() {
  // Original behavior - use function.apply to preserve context
  const ret = oldShow.apply(this, arguments)

  // Your source code
  this.removeClass('hidden')

  return ret
}
Kevin Campion
  • 2,223
  • 2
  • 23
  • 29