Reputation: 36166
I want to build a simple jQuery plugin, but I don't know how to start, I read a few articles and even tried to learn code of a few popular plugins, but it draw me even deeper into confusion.
Show me please a starter template. Let's say for the sake of example I should get something, that I can call like that:
$("a").myMessagePlugin();
Now, everytime somebody clicks a link it should just popup an alert and show that link.
Thank you
Upvotes: 1
Views: 170
Reputation: 980
it is recomended you specify undefined as well (I'm using previous example as base, thanks)
Also a good practice is to define defaults for the options and extend them using $.extend
(function($, undefined) {
$.fn.myPlugin= function(options) {
var opts = $.extend($.fn.myPlugin.defaults, options);
return this.click( function() { //jQuery object, to be returned
alert(this.href); //html element
});
}
$.fn.myPlugin.defaults = {
"option1": 1,
"option2": 2
}
})(jQuery);
Upvotes: 1
Reputation: 32598
The other answers are mostly correct, but if you want to use the dollar sign, wrap it in an anonymous function and pass the jQuery object. Otherwise, you run the risk of conflicting with other libraries.
(function($) {
$.fn.myMessagePlugin = function(options) {
return this.click( function() { //jQuery object, to be returned
alert(this.href); //html element
});
}
})(jQuery);
Upvotes: 2
Reputation: 69905
Whenever you write a jQuery
plugin make sure you return the jQuery
object because it will help in chaining the jQuery
methods.
$.fn.myMessagePlugin = function(options) {
return this.each(function(){
//plugin logic here
$(this).click( function() {
alert(this.href);
});
});
}
Upvotes: 3