jQuery is an awesome javascript library which is used in almost every websites nowadays. jQuery extends to different plugins libraries that will reduce our work in web development. For example,jQuery Validation Plugin, Smoke, etc are some form validation plugins in jQuery. Many plugins are available in the web but some times we may want to develop our own jQuery plugin for customisation.
Yes of course we can develop our own plugin, which can be used in any websites. In this tutorial we are going to develop a simple plugin in which we can change the colour and background colour of an element.
Normally a plugin will come up with a .js file and here you can create a mypulgin.js file and which should be included in the page. Add the following block of code in your myplugin.js file
(function ( $ ) { $.fn.myPlugin = function( options ) { //Add default options. var settings = $.extend({ //default values color: "#000000", backgroundColor: "#ffffff" }, options ); //Add the css attributes to the element return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
The plugin is ready to use now. Add the js file to your page and use the plugin. Below is an example of using it,
<script> $("div").myPlugin({ color: "#000000", backgroundColor: "#ffffff" }); </script>
The above code should change the colour and background colour of the div. This is just an example and you can extend the functionality based on your need. Please don’t forget to add jquery library before adding your plugin file in the page.
That’s all what you need to learn from here to create a basic jQuery plugin. Hope you like it. Please feel free to contact me if you have any queries – me@praveenpb.com
Add new comment