Extending jQuery is not working…?

I'm not getting how to extend jQuery... I have the following code:

jQuery.fn.extend({

    whatever : function () {
        alert('yeah');
    }

});

Which should be giving me a $.whatever function, no? But when I check it, or try to run it: zilch.

Check out this fiddle: http://jsfiddle.net/66gpf/

I checked the docs and it seems good to me... SO, what am I doing wrong??

Answers:

Answer

jQuery.fn is a reference to jQuery.prototype. So when you do jQuery.fn.extend, you adding a property to the prototype, not to jQuery itself. The whatever function will exist on all jQuery instances.

jQuery.fn.extend({
    whatever : function () {
        alert('yeah');
    }
});

$('#a_selector').whatever();

Docs: http://api.jquery.com/jquery.fn.extend/

P.S. If you want the function to exist as $.whatever instead of only on jQuery object instances, then add it to $ instead of $.fn.

jQuery.extend(jQuery, {
    whatever : function () {
        alert('yeah');
    }
});

$.whatever();
Answer

you need to use $('body').html( typeof $('body').whatever ); because it does not add the whatever as a property of jQuery static object

$('body').html(typeof $('body').whatever);

Demo: Fiddle

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.