Getting Started With Javascript Plugins

One can get started with creating javascript plugins easily. A to do guide for creating a simple pliugin is given here.

reddish.js
1
2
3
$.fn.reddish = function() {
  this.css( "color", "red" );
};

This defines the plugin. It will add red colour to any element on which reddish method will be called.

Now we can implement this :

index.html
1
2
3
4
5
6
7
<div class='div_one'>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.   </div>
<div class='div_two'>Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. </div>
<div class='div_three'>Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</div>

and

custom.js
1
2
3
4
5
6
7
$( document ).ready(function() {
...
...
$('.div_one, .div_two').reddish();
...
...
});

This will call the the method defined in reddish.js and change the color for the div_one and div_two, but div_three will remain unaffected.

Comments