Reusable Web
  Components
  with jQuery and jQuery UI


  Slides By: Ynon Perek.

  http://ynonperek.com
Friday, February 8, 13
Agenda
                         • Reusable Components
                         • jQuery Plugins Into
                         • Writing Our First Plugin
                         • Popular jQuery Plugins
                         • jQuery UI Widgets
                         • Writing Our First Widget

Friday, February 8, 13
Resources


                         • Microsoft’s Project Silk:

                           http://msdn.microsoft.com/en-us/
                           library/hh396380.aspx




Friday, February 8, 13
Reusable Component


                         • Markup + Style + JavaScript
                         • All are optional




Friday, February 8, 13
Why Reuse

                         • Use same code
                           within the same
                           project

                         • Use same code
                           within different
                           projects




Friday, February 8, 13
The Hows


                         • Roll Your Own

                         • Extend Existing
                           Framework




Friday, February 8, 13
The Hows


                         • Roll Your Own

                         • Extend Existing
                           Framework




Friday, February 8, 13
jQuery Plugins



Friday, February 8, 13
jQuery Plugin


                         • Reusable JS Code
                         • Uses jQuery




Friday, February 8, 13
Example Plugins
                         • http://paweldecowski.github.com/
                           jQuery-CreditCardValidator/
                         • http://anthonyterrien.com/knob/
                         • http://www.datatables.net/
                         • http://stevenbenner.github.com/
                           jquery-powertip/


Friday, February 8, 13
Common Concepts

        $('#example').dataTable();

           $(".dial").knob();

        $('.info').powerTip({
           placement: 'ne'
        });



Friday, February 8, 13
Common Concepts

                         • Plugins add
                           functionality to     $('#example').dataTable();

                           jQuery Objects       $(".dial").knob();

                                                $('.info').powerTip({
                         • Can take options        placement: 'ne'
                                                });

                         • Launch and Forget




Friday, February 8, 13
• jQuery plugins are just organized
                           reusable code




Friday, February 8, 13
Let’s Write A Plugin



Friday, February 8, 13
Outliner Plugin


                         • Our plugin will add outline to an
                           element




Friday, February 8, 13
Writing A Plugin

                                  // Outside $ may be another library
                                   
                                  (function($) {
         • Protect the $ with a    
           self invoking           
                                    // But inside it's jQuery
           function                
                                  }(jQuery));




Friday, February 8, 13
Writing A Plugin

                                (function($) {
         • Extend jQuery with    
           your plugin name       $.fn.outliner = function() {
                                 
                                  };
         • Plugin is just a      
                                 
           function             }(jQuery));




Friday, February 8, 13
Writing A Plugin

         • Do you thing
                             (function($) {
                              
         • this is the         $.fn.outliner = function() {
                                  this.css('outline', '2px solid blue');
           jQuery object       };
                              
           you’re             
           working on        }(jQuery));




Friday, February 8, 13
Writing A Plugin

                             (function($) {
                              
         • end with            $.fn.outliner = function() {
           return this           this.css('outline', '2px solid blue');
                                 return this;
           to allow            };
                              
           chaining           
                             }(jQuery));




Friday, February 8, 13
Using The Plugin

                         • Here’s how a user may add outline




      $('div').outliner();




Friday, February 8, 13
Using The Plugin
                         • Here’s how a user may add outline
                         • Or with chaining



      $('div').outliner().html('Cool Plugin');




Friday, February 8, 13
Adding Options


                         • Some users like
                           different color

                         • Some users like
                           different width




Friday, February 8, 13
Adding Options


                         • Some users like
                                             $('div').outliner({
                           different color
                                               color: 'red',
                                               width: 2
                         • Some users like
                                             });
                           different width




Friday, February 8, 13
Adding Options
  (function($) {
   
    $.fn.outliner = function( options ) {
      options = $.extend({}, $.fn.outliner.defaults, options);
   
      return this.css({
        'outline-color' : options.color,
        'outline-width' : options.width + 'px',
        'outline-style' : 'solid'
      });
    };
   
    $.fn.outliner.defaults = {
      color: 'blue',
      width: 1
    };
   
  }(jQuery));

Friday, February 8, 13
Basic Plugin Review

                         • Protect The $
                         • Add Your Plugin To $.fn
                         • Return this
                         • Add options and defaults



Friday, February 8, 13
Plugin Lab
                         • Write a “Same Text” plugin
                         • Activated on input elements
                         • When a user changes text in one input,
                           text should be copied to other inputs
                         • Add validation regexp as an option.
                           Copy only if text matches validation


Friday, February 8, 13
Q&A




Friday, February 8, 13
DOM
        Manipulating
        Plugins


Friday, February 8, 13
Simple Autocomplete


                         • Let’s write a simple
                           autocomplete
                           plugin




Friday, February 8, 13
Solution Outline

                                            var list_el = $('<ul
                                            class="autocomplete"></ul>');
                                             
                         • Create The New   list_el.on('click', 'li',
                           List Element                 function(ev) {
                                            // type code here
                                            });
                         • Bind Event        
                                            self.on('input', function(ev) {
                           Handlers         // type code here
                                            });




Friday, February 8, 13
Autocomplete Takeaways

                         • A plugin can use accompanying CSS
                           file
                         • A plugin can “bind” event handlers
                         • Can maintain state using closures




Friday, February 8, 13
Plugin Limitations


                         • Hard to maintain state
                         • Hard to destroy
                         • Hard to extend




Friday, February 8, 13
Meet
        jQuery UI
        Extensible UI Library Build
        On Top of jQuery




Friday, February 8, 13
What’s In The Box


                         • UI Framework
                         • UI Components
                         • Themes Framework




Friday, February 8, 13
jQuery UI Core

   Autocomplete
   Widget

   Tabs                      Widgets   Enhanced
   Widget                    Factory   jQuery Plugin

   Gallery
   Widget


Friday, February 8, 13
Our First Widget
  $(function($) { 
    $.widget('my.filler', {
      _create: function() {
        this.element.html('Hello World');
      }
    });
  }(jQuery));

  // use the widget like a plugin
  var widget = $('div').filler();


Friday, February 8, 13
jQUI Basics

                         • A widget is an object (not a function)
                         • _create is the entry point
                         • this.element is the DOM element
                         • widget name is namespaced



Friday, February 8, 13
Widget Lifecycle


                         • _create is called on creation
                         • _init is the default method
                         • _destroy terminates the widget




Friday, February 8, 13
Fixing Our First Widget
  $(function($) {
   
    $.widget('my.filler', {
      _create: function() {
        this.data = { previousContent: this.element.html()   }
        this.element.html('Hello World');
      },
      _destroy: function() {
        this.element.html( this.data.previousContent );
      }
    });
  }(jQuery));



  // later in code
  widget.filler('destroy');

Friday, February 8, 13
Widget Customizations

                         • A jQuery UI Widget can take options
                           (just like with plugins)
                         • Options are automatically merged for
                           you in the factory
                         • Can respond “live” to changes



Friday, February 8, 13
Start With The Defaults
  $(function($) {
   
    $.widget('my.filler', {
      options: {
        text: 'Hello World'
      },
   
      _create: function() {
         ...
        this.element.html( this.option('text') );
      },
   
      _destroy: function() { ... }
    });
   
   
  }(jQuery));



Friday, February 8, 13
Create Customized


      • Pass the options
        when creating your       var widget = $('div').filler({
                                   text: 'Customization Is Cool'
        widget                   });

      • No need to pass all.




Friday, February 8, 13
Changing Options
       • A user can get or set options at runtime
       • Use the public method option

      var widget = $('div').filler({
        text: 'Customization Is Cool'
      });
       
      console.log( widget.filler('option', 'text') );
      widget.filler('option', 'text', 'Bye bye');
      console.log( widget.filler('option', 'text') );




Friday, February 8, 13
Changing Options
       • A user can get or set options at runtime
       • Use the public method option

      var widget = $('div').filler({
        text: 'Customization Is Cool'
      });
       
      console.log( widget.filler('option', 'text') );
      widget.filler('option', 'text', 'Bye bye');
      console.log( widget.filler('option', 'text') );



                         Widget Name      Method Name
Friday, February 8, 13
Handling Changes

    • A widget can detect
      option change and
                                _setOption: function(key, val) {
      respond to them by          this._superApply(arguments);
                                 
      implementing                this.element.html(
      _setOption method             this.option('text') );
                                },
                                 
    • Remember to call
      super



Friday, February 8, 13
Other Public Methods
        • Every method of
          your object
          which starts
          with a letter is
          public             widget.filler('doSomething')

        • Call it from the
          outside using
          the widget


Friday, February 8, 13
jQuery UI Events
                         • Use _trigger to
                           trigger a custom
                           event              _create: function() {
                                                var self = this;
                         • Arguments:           setTimeout(function() {
                                                  self._trigger('done');
                           • event name         }, 2000);

                                              },
                           • event object

                           • hash data


Friday, February 8, 13
jQuery UI Events


                         • Can bind event
                                                  var widget = $('div').filler({
                           handlers                 done: function() {
                                                      console.log('Done !');
                                                    }
                         • Better yet - pass      });
                           callbacks as options




Friday, February 8, 13
Extending Widgets
                         • Extend a widget by passing it as the
                           second argument to widget function


       $.widget('my.complex', $.my.simple, {
         // code goes here
       });
        



Friday, February 8, 13
Q&A




Friday, February 8, 13
Lab1

                         • Write a Progress Bar Widget
                         • Allow a user to change progress value
                         • Bonus: Use HTML Progress Element
                           when supported




Friday, February 8, 13
Lab2

                         • Write a plugin to limit characters in an
                           input field
                         • Should show how many chars left, and
                           prevent going beyond the limit




Friday, February 8, 13
Selected
        Plugins
        jQuery UI
        Other jQuery Plugins




Friday, February 8, 13
jQuery UI Widgets


                         • Demo page + Documentation:
                           http://jqueryui.com/demos/




Friday, February 8, 13
Equalize
  http://tsvensen.github.com/equalize.js/




Friday, February 8, 13
Gridster
   http://gridster.net/




Friday, February 8, 13
Zoomooz
    http://janne.aukia.com/zoomooz/




Friday, February 8, 13
dd Slick
   http://designwithpc.com/Plugins/ddSlick




Friday, February 8, 13
jQuery Complexity
  http://danpalmer.me/jquery-complexify/




Friday, February 8, 13
Credit Card Validator
  http://paweldecowski.github.com/jQuery-
  CreditCardValidator/




Friday, February 8, 13
Filtering Content
   http://luis-almeida.github.com/filtrify/




Friday, February 8, 13
Fresco
   http://www.frescojs.com/




Friday, February 8, 13
Responsive Slider
 http://responsive-slides.viljamis.com/




Friday, February 8, 13
Trunk8
   http://jrvis.com/trunk8/




Friday, February 8, 13
Tooltipster
   http://calebjacob.com/tooltipster/




Friday, February 8, 13
Page Slide
   http://srobbin.com/jquery-plugins/pageslide/




Friday, February 8, 13
Data Tables
   http://www.datatables.net/




Friday, February 8, 13
Masonry
  http://masonry.desandro.com/




Friday, February 8, 13
What Next

                         • Find more plugins at:
                           http://plugins.jquery.com/
                         • Build your own plugins and
                           components




Friday, February 8, 13
Thanks For Listening

                         • Ynon Perek
                         • Talk to me: ynon@ynonperek.com
                         • Find more slides:
                           http://ynonperek.com




Friday, February 8, 13

Writing Reusable Web Components with jQuery and jQuery UI

  • 1.
    Reusable Web Components with jQuery and jQuery UI Slides By: Ynon Perek. http://ynonperek.com Friday, February 8, 13
  • 2.
    Agenda • Reusable Components • jQuery Plugins Into • Writing Our First Plugin • Popular jQuery Plugins • jQuery UI Widgets • Writing Our First Widget Friday, February 8, 13
  • 3.
    Resources • Microsoft’s Project Silk: http://msdn.microsoft.com/en-us/ library/hh396380.aspx Friday, February 8, 13
  • 4.
    Reusable Component • Markup + Style + JavaScript • All are optional Friday, February 8, 13
  • 5.
    Why Reuse • Use same code within the same project • Use same code within different projects Friday, February 8, 13
  • 6.
    The Hows • Roll Your Own • Extend Existing Framework Friday, February 8, 13
  • 7.
    The Hows • Roll Your Own • Extend Existing Framework Friday, February 8, 13
  • 8.
  • 9.
    jQuery Plugin • Reusable JS Code • Uses jQuery Friday, February 8, 13
  • 10.
    Example Plugins • http://paweldecowski.github.com/ jQuery-CreditCardValidator/ • http://anthonyterrien.com/knob/ • http://www.datatables.net/ • http://stevenbenner.github.com/ jquery-powertip/ Friday, February 8, 13
  • 11.
    Common Concepts  $('#example').dataTable(); $(".dial").knob(); $('.info').powerTip({     placement: 'ne' }); Friday, February 8, 13
  • 12.
    Common Concepts • Plugins add functionality to  $('#example').dataTable(); jQuery Objects $(".dial").knob(); $('.info').powerTip({ • Can take options     placement: 'ne' }); • Launch and Forget Friday, February 8, 13
  • 13.
    • jQuery pluginsare just organized reusable code Friday, February 8, 13
  • 14.
    Let’s Write APlugin Friday, February 8, 13
  • 15.
    Outliner Plugin • Our plugin will add outline to an element Friday, February 8, 13
  • 16.
    Writing A Plugin // Outside $ may be another library   (function($) { • Protect the $ with a   self invoking     // But inside it's jQuery function   }(jQuery)); Friday, February 8, 13
  • 17.
    Writing A Plugin (function($) { • Extend jQuery with   your plugin name   $.fn.outliner = function() {     }; • Plugin is just a     function }(jQuery)); Friday, February 8, 13
  • 18.
    Writing A Plugin • Do you thing (function($) {   • this is the   $.fn.outliner = function() {      this.css('outline', '2px solid blue'); jQuery object   };   you’re   working on }(jQuery)); Friday, February 8, 13
  • 19.
    Writing A Plugin (function($) {   • end with   $.fn.outliner = function() { return this     this.css('outline', '2px solid blue');     return this; to allow   };   chaining   }(jQuery)); Friday, February 8, 13
  • 20.
    Using The Plugin • Here’s how a user may add outline $('div').outliner(); Friday, February 8, 13
  • 21.
    Using The Plugin • Here’s how a user may add outline • Or with chaining $('div').outliner().html('Cool Plugin'); Friday, February 8, 13
  • 22.
    Adding Options • Some users like different color • Some users like different width Friday, February 8, 13
  • 23.
    Adding Options • Some users like $('div').outliner({ different color   color: 'red',   width: 2 • Some users like }); different width Friday, February 8, 13
  • 24.
    Adding Options (function($) {     $.fn.outliner = function( options ) {     options = $.extend({}, $.fn.outliner.defaults, options);       return this.css({       'outline-color' : options.color,       'outline-width' : options.width + 'px',       'outline-style' : 'solid'     });   };     $.fn.outliner.defaults = {     color: 'blue',     width: 1   };   }(jQuery)); Friday, February 8, 13
  • 25.
    Basic Plugin Review • Protect The $ • Add Your Plugin To $.fn • Return this • Add options and defaults Friday, February 8, 13
  • 26.
    Plugin Lab • Write a “Same Text” plugin • Activated on input elements • When a user changes text in one input, text should be copied to other inputs • Add validation regexp as an option. Copy only if text matches validation Friday, February 8, 13
  • 27.
  • 28.
    DOM Manipulating Plugins Friday, February 8, 13
  • 29.
    Simple Autocomplete • Let’s write a simple autocomplete plugin Friday, February 8, 13
  • 30.
    Solution Outline var list_el = $('<ul class="autocomplete"></ul>');   • Create The New list_el.on('click', 'li', List Element function(ev) { // type code here }); • Bind Event   self.on('input', function(ev) { Handlers // type code here }); Friday, February 8, 13
  • 31.
    Autocomplete Takeaways • A plugin can use accompanying CSS file • A plugin can “bind” event handlers • Can maintain state using closures Friday, February 8, 13
  • 32.
    Plugin Limitations • Hard to maintain state • Hard to destroy • Hard to extend Friday, February 8, 13
  • 33.
    Meet jQuery UI Extensible UI Library Build On Top of jQuery Friday, February 8, 13
  • 34.
    What’s In TheBox • UI Framework • UI Components • Themes Framework Friday, February 8, 13
  • 35.
    jQuery UI Core Autocomplete Widget Tabs Widgets Enhanced Widget Factory jQuery Plugin Gallery Widget Friday, February 8, 13
  • 36.
    Our First Widget $(function($) {    $.widget('my.filler', {     _create: function() {       this.element.html('Hello World');     }   }); }(jQuery)); // use the widget like a plugin var widget = $('div').filler(); Friday, February 8, 13
  • 37.
    jQUI Basics • A widget is an object (not a function) • _create is the entry point • this.element is the DOM element • widget name is namespaced Friday, February 8, 13
  • 38.
    Widget Lifecycle • _create is called on creation • _init is the default method • _destroy terminates the widget Friday, February 8, 13
  • 39.
    Fixing Our FirstWidget $(function($) {     $.widget('my.filler', {     _create: function() {       this.data = { previousContent: this.element.html() }       this.element.html('Hello World');     },     _destroy: function() {       this.element.html( this.data.previousContent );     }   }); }(jQuery)); // later in code widget.filler('destroy'); Friday, February 8, 13
  • 40.
    Widget Customizations • A jQuery UI Widget can take options (just like with plugins) • Options are automatically merged for you in the factory • Can respond “live” to changes Friday, February 8, 13
  • 41.
    Start With TheDefaults $(function($) {     $.widget('my.filler', {     options: {       text: 'Hello World'     },       _create: function() { ...       this.element.html( this.option('text') );     },       _destroy: function() { ... }   });     }(jQuery)); Friday, February 8, 13
  • 42.
    Create Customized • Pass the options when creating your var widget = $('div').filler({   text: 'Customization Is Cool' widget }); • No need to pass all. Friday, February 8, 13
  • 43.
    Changing Options • A user can get or set options at runtime • Use the public method option var widget = $('div').filler({   text: 'Customization Is Cool' });   console.log( widget.filler('option', 'text') ); widget.filler('option', 'text', 'Bye bye'); console.log( widget.filler('option', 'text') ); Friday, February 8, 13
  • 44.
    Changing Options • A user can get or set options at runtime • Use the public method option var widget = $('div').filler({   text: 'Customization Is Cool' });   console.log( widget.filler('option', 'text') ); widget.filler('option', 'text', 'Bye bye'); console.log( widget.filler('option', 'text') ); Widget Name Method Name Friday, February 8, 13
  • 45.
    Handling Changes • A widget can detect option change and _setOption: function(key, val) { respond to them by   this._superApply(arguments);   implementing   this.element.html( _setOption method this.option('text') ); },   • Remember to call super Friday, February 8, 13
  • 46.
    Other Public Methods • Every method of your object which starts with a letter is public widget.filler('doSomething') • Call it from the outside using the widget Friday, February 8, 13
  • 47.
    jQuery UI Events • Use _trigger to trigger a custom event _create: function() {   var self = this; • Arguments:   setTimeout(function() {     self._trigger('done'); • event name   }, 2000); }, • event object • hash data Friday, February 8, 13
  • 48.
    jQuery UI Events • Can bind event var widget = $('div').filler({ handlers   done: function() {     console.log('Done !');   } • Better yet - pass }); callbacks as options Friday, February 8, 13
  • 49.
    Extending Widgets • Extend a widget by passing it as the second argument to widget function $.widget('my.complex', $.my.simple, {   // code goes here });   Friday, February 8, 13
  • 50.
  • 51.
    Lab1 • Write a Progress Bar Widget • Allow a user to change progress value • Bonus: Use HTML Progress Element when supported Friday, February 8, 13
  • 52.
    Lab2 • Write a plugin to limit characters in an input field • Should show how many chars left, and prevent going beyond the limit Friday, February 8, 13
  • 53.
    Selected Plugins jQuery UI Other jQuery Plugins Friday, February 8, 13
  • 54.
    jQuery UI Widgets • Demo page + Documentation: http://jqueryui.com/demos/ Friday, February 8, 13
  • 55.
  • 56.
    Gridster http://gridster.net/ Friday, February 8, 13
  • 57.
    Zoomooz http://janne.aukia.com/zoomooz/ Friday, February 8, 13
  • 58.
    dd Slick http://designwithpc.com/Plugins/ddSlick Friday, February 8, 13
  • 59.
    jQuery Complexity http://danpalmer.me/jquery-complexify/ Friday, February 8, 13
  • 60.
    Credit Card Validator http://paweldecowski.github.com/jQuery- CreditCardValidator/ Friday, February 8, 13
  • 61.
    Filtering Content http://luis-almeida.github.com/filtrify/ Friday, February 8, 13
  • 62.
    Fresco http://www.frescojs.com/ Friday, February 8, 13
  • 63.
  • 64.
    Trunk8 http://jrvis.com/trunk8/ Friday, February 8, 13
  • 65.
    Tooltipster http://calebjacob.com/tooltipster/ Friday, February 8, 13
  • 66.
    Page Slide http://srobbin.com/jquery-plugins/pageslide/ Friday, February 8, 13
  • 67.
    Data Tables http://www.datatables.net/ Friday, February 8, 13
  • 68.
  • 69.
    What Next • Find more plugins at: http://plugins.jquery.com/ • Build your own plugins and components Friday, February 8, 13
  • 70.
    Thanks For Listening • Ynon Perek • Talk to me: ynon@ynonperek.com • Find more slides: http://ynonperek.com Friday, February 8, 13