Your Friend
Your Friend

Reputation: 1149

jquery very simple plugin, very basic

can we call jquery plugin like this? this is in my plugin file

    (function($) {

    $.fn.alertme=function(){
    alert('just testing');
    };


    }(jQuery));

i have included the plugin file ,, and calling the function on my home page...

    <script>
    $(document).ready( function() {

    alertme();
    });


    </script>

I see an error message on console log Uncaught ReferenceError: alertme is not defined i even tried return alert('just testing'); ,, how do we fix this?

Upvotes: 2

Views: 58

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You added the function to $.fn, which is an alias to the prototype of the jQuery constructor. That means your function is attached to all objects created as $(someArgs).

Call your function on a jQuery object, for example

$(document).ready( function() {
   $(document).alertme();
});

or

$(document).ready( function() {
   $({}).alertme();
});

or even

$(document).ready( function() {
   $().alertme();
});

But there's no point in making a jQuery plugin if you don't use this (the jQuery object) in the function. Usually you'd do something like this :

// logs all elements of the jQuery collection
$.fn.logme=function(){
  this.each(function(){
    console.log(this);
  })
};

$(document).ready( function() {
   $('p').logme();
});

Upvotes: 4

Sridhar R
Sridhar R

Reputation: 20408

You must call using jQuery object

Try this

$(document).ready( function() {
   $(document).alertme();
});

DEMO

Upvotes: 0

Related Questions