1

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));
    }
});

1 Answer 1

4

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);
};
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for being faster than me :). I also thought about the same variable name xD
You should at least refactor to avoid introducing the originalHide global variable.
@plalx: Who said this was the global scope? I don’t really find the extra IIFEs necessary for short snippets…
@minitech Perhaps you don't and an experienced JS developer would understand that it's implicit here, however people asking these kind of questions aren't experienced JS developers. Therefore, I believe it's more appropriate not to infer the audience's knowledge and provide a solution which is as complete as possible.
@plalx: If the asker of a question doesn’t understand how to change scope, all the more reason not to add confusion. Globals aren’t so bad that they warrant a mention in every answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.