90 likes | 222 Views
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. <! doctype html> <html> <head>
E N D
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 <!doctype html> <html> <head> <script type="text/javascript" src="jquery.js"></script> // include jQuery itself <script type="text/javascript"> $(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 }); }); </script> </head> <body> <a href="http://jquery.com/">jQuery</a> </body> </html>
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.checkbox.js[2] 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; } }); };
Index.html <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.checkbox.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#cbox2").check("on"); $("#cbox3").check("on"); }); </script> </head> <body> <form> here are some checkboxes </br> notice how the 2nd and 3rd boxes </br> are automatically checked.</br> <input type="checkbox" id="cbox1" /> </br> <input type="checkbox" id="cbox2" /> </br> <input type="checkbox" id="cbox3" /> </br> <input type="checkbox" id="cbox4" /> </br> </form> </body> </html>
Sources • [1] http://en.wikipedia.org/wiki/JQuery#jQuery_Plug-ins • [2] http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery