JQuery Plugins Samuel Zweig CMPS 183
A bit about JQuery Lightweight JavaScript library Used by over 27% of the top 10,000 most visited websites [1] Open Source
A simple JQuery example // include jQuery itself $(document).ready(function(){ // wait for DOM to be ready $("a").click(function(event){ // select all a elements // click () is a method of the JQuery object event.preventDefault(); // prevent default behavior $(this).hide("slow"); // cause link to slowly disappear }); jQuery
JQuery Plugins Range from simple (a few lines of code) to very complex Easy to write own plugins Easy to use other developer’s plugins Allow for the creation of elegant web apps with minimal effort. A plugin is an extension of the JQuery object
Making your own plugin Motivation: prevent excessive code repetition
Basic Steps 1. Create a file called jquery.[your_plugin_name].js 2. Create a method that extends the jQuery object. 3. Create default settings for your method 4. Create documentation (if you are going to share your plugin)
Example plugin | Checkboxes jQuery.fn.check = function(mode) { // if mode is undefined, use 'on' as default var mode = mode || 'on'; return this.each(function() { switch(mode) { case 'on': this.checked = true; break; case 'off': this.checked = false; break; case 'toggle': this.checked = !this.checked; break; } }); }; jquery.checkbox.js [2]
$(document).ready(function() { $("#cbox2").check("on"); $("#cbox3").check("on"); }); here are some checkboxes notice how the 2nd and 3rd boxes are automatically checked. Index.html
Sources [1] _Plug-ins _Plug-ins [2] arted_with_jQuery arted_with_jQuery