ch2o
ch2o

Reputation: 839

How I can add functionality to a jQuery method?

How I can add functionality to a jQuery method? For example, when using hide on an element (<a> or <p> or something else):

HTML

<a href="#">click me</a>

jQuery

$("a").hide()

I tried creating a type of plugin, but I want to keep the native functionality and then add more.

jQuery.fn.extend({
    hide: function () {
        alert("hidden element: " + $(this));
    }
});

Upvotes: 1

Views: 49

Answers (1)

Ry-
Ry-

Reputation: 224867

The easiest way, of course, would be to give it a different name. If you really don’t want to do that, you can keep a reference to the original method, then pass both this and any received arguments using Function.prototype.apply:

var originalHide = jQuery.fn.hide;

jQuery.fn.hide = function () {
    alert('hidden element: ' + this); // == $(this); neither is meaningful
    return originalHide.apply(this, arguments);
};

Upvotes: 4

Related Questions