Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a simple fn.extend not work?

Tags:

jquery

I'm sure this is something simple, but I'm missing it - why does the following inside of a <script> tag not work and pop up an alert?

jQuery.fn.extend({
    sayHi: function () {
        alert('hello!');
    }
});

$(document).ready(function () {
    jQuery.sayHi();
});
like image 753
Brandon Avatar asked Jan 22 '14 02:01

Brandon


People also ask

What is FN extend?

fn. extend() method extends the jQuery prototype ( $. fn ) object to provide new methods that can be chained to the jQuery() function.

What does jQuery fn mean?

fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn. something = function{}

How to extend function in jQuery?

This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive . target: This parameter is the object to extend.


1 Answers

Because you set jQuery.fn.sayHi, not jQuery.sayHi (which is undefined, hence you get a runtime error).

Methods you set on jQuery.fn are available on selections (jQuery objects) only, not the jQuery function.

jQuery('body').sayHi(); would work.

For more information about plugin development, see http://learn.jquery.com/plugins/basic-plugin-creation/.

like image 182
Felix Kling Avatar answered Oct 02 '22 19:10

Felix Kling