Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Contextual jQuery (2012)

Doug Neiner
February 10, 2012

Contextual jQuery (2012)

This was an updated version of my original Contextual jQuery talk from Boston 2010. The syntax has been updated for jQuery 1.7's `on` method. More examples were added, and some examples were changed to make the meaning more clear.

Doug Neiner

February 10, 2012
Tweet

More Decks by Doug Neiner

Other Decks in Programming

Transcript

  1. CONTEXTUAL jQuery Doug Neiner
    CONTEXTUAL jQuery

    View full-size slide

  2. CONTEXTUAL jQuery Doug Neiner
    JQUERY CODE STYLES
    • Declarative
    • Dynamic
    • Contextual

    View full-size slide

  3. CONTEXTUAL jQuery Doug Neiner
    DECLARATIVE
    • Heavy use of ID’s
    • All traditional event binding
    • Often repeated code with slight variations
    • Changes to HTML often require changes to JS and vice versa.
    • Large number of selectors running on Document Ready

    View full-size slide

  4. CONTEXTUAL jQuery Doug Neiner
    DECLARATIVE
    $(  document  ).ready(  function  ()  {
       var  $form1  =  $(  "#form1"  ),
               $form2  =  $(  "#form2"  );
       
       $("#form1Submit").click(function  (  e  )  {
           e.preventDefault();
           $form1.submit();
       });
       $("#form2Submit").click(function  (  e  )  {
           e.preventDefault();
           $form2.submit();
       });
    });

    View full-size slide

  5. CONTEXTUAL jQuery Doug Neiner
    DYNAMIC
    • Heavy use of classes, simple selectors
    • Mixture of traditional event binding and delegated binding
    • Less repeated code
    • Changes to HTML still may require changes to JS
    • Many selectors still running on Document Ready

    View full-size slide

  6. CONTEXTUAL jQuery Doug Neiner
    DYNAMIC
    $(  document  ).ready(  function  ()  {
       var  $form1  =  $(  "#form1"  ),
               $form2  =  $(  "#form2"  );
       
       $(  "a.formSubmit"  ).click(  function  (  e  )  {
           e.preventDefault();
           if  (  this.id  ===  "form1Submit"  )  {
               $form1.submit();
           }  else  {
               $form2.submit();
           }
       });
    });

    View full-size slide

  7. CONTEXTUAL jQuery Doug Neiner
    CONTEXTUAL
    • Minimal use of ID’s, some classes
    • Leverages selectors and traversing
    • Very little repeated code
    • HTML follows a convention so edits
    require less changes to the JS
    • Virtually no selectors running on Document Ready

    View full-size slide

  8. CONTEXTUAL jQuery Doug Neiner
    CONTEXTUAL
    $(document).on("click",  "form  a.submit",  function  (e)  {
           e.preventDefault();
           $(  this  )
               .closest(  "form"  )
               .submit();
       }
    );

    View full-size slide

  9. CONTEXTUAL jQuery Doug Neiner
    BENEFITS
    of Contextual jQuery

    View full-size slide

  10. CONTEXTUAL jQuery Doug Neiner
    BENEFITS
    • Faster Flexible and More Responsible Code
    • Focussed Use of Resources
    • Less Code Overall
    • Easier to maintain
    • Easy to reuse

    View full-size slide

  11. CONTEXTUAL jQuery Doug Neiner
    IMPLEMENTATION

    View full-size slide

  12. CONTEXTUAL jQuery Doug Neiner
    IMPLEMENTATION
    Minimize Setup
    Delegated Events
    Traversal, Filters and Selectors
    HTML Conventions

    View full-size slide

  13. CONTEXTUAL jQuery Doug Neiner
    MINIMIZE SETUP
    • Use CSS classes to control states
    • Always opt for just-in-time initialization

    View full-size slide

  14. CONTEXTUAL jQuery Doug Neiner
    HANDLING INITIAL STATE



         
         Sample
         <br/>            html.no-­‐js  .js,  html.js  .no-­‐js  {  display:  none  }<br/>      
         <br/>          document.documentElement.className  =  <br/>              document.documentElement.className.replace(  "no-­‐js",  "js"  );<br/>      


       Learn  About  Us
         Something  Amazing!  

    View full-size slide

  15. CONTEXTUAL jQuery Doug Neiner
    LEVERAGING MODERNIZR
    Find  My  Location
    .find-­‐location  {  display:  none;  }
    .geolocation  .find-­‐location  {  display:  inline;  }
    if  (  Modernizr.geolocation  )  {
         $(  document  ).on(  "click",  ".find-­‐location",  function  ()  {
             …
         });
    }

    View full-size slide

  16. CONTEXTUAL jQuery Doug Neiner
    CREATE YOUR OWN
    My  Account
    .user-­‐action  {  display:  none;  }
    .signed-­‐in  .user-­‐action  {  display:  inline;  }
    function  authenticate()  {
       //  Lots  of  important  code  here
       $(  document  ).addClass(  "signed-­‐in"  );
    }

    View full-size slide

  17. CONTEXTUAL jQuery Doug Neiner
    JUST IN TIME INITIALIZATION
    • Users don't generally use every part of every page all the time.
    • Set up areas of your page only when needed.
    • Leverage user actions or probable user actions as an indication
    of what to initialize.

    View full-size slide

  18. CONTEXTUAL jQuery Doug Neiner
    USER ACTIONS
    • click
    • mouseenter / mouseleave
    • scrolling
    • focusin / focusout
    • metrics

    View full-size slide

  19. CONTEXTUAL jQuery Doug Neiner
    DECLARATIVE DIALOG
    $(  document  ).ready(  function  (e)  {
         var  $contactDialog  =
               $(  "#contact-­‐dialog"  ).dialog({  autoOpen:  false  });
         $(  "#openContactForm"  ).click(  function  (  e  )  {
             e.preventDefault();
             $contactDialog.dialog(  "open"  );
         });
    });

    View full-size slide

  20. CONTEXTUAL jQuery Doug Neiner
    CONTEXTUAL DIALOG
    $(  document  ).on(  "click",  "a[href^=contact]",  function  (e)  {
       e.preventDefault();
       var  $contactDialog  =  $(  "#contact-­‐dialog"  );  
       if  (  $contactDialog.data(  "dialog"  )  )  {
             $contactDialog.dialog(  "open"  );
       }  else  {
             $contactDialog.dialog();
       }
    });

    View full-size slide

  21. CONTEXTUAL jQuery Doug Neiner
    WRITE CODE LIKE YOU
    SPEND MONEY
    Opt to pay a little more later so you
    don't risk losing it all on something that never happens.

    View full-size slide

  22. CONTEXTUAL jQuery Doug Neiner
    DELEGATED EVENTS

    View full-size slide

  23. CONTEXTUAL jQuery Doug Neiner
    TRADITIONAL EVENTS


    document

    Click Handler
    Click Handler
    $(  "a"  )
       .bind("click",  …)

    View full-size slide

  24. CONTEXTUAL jQuery Doug Neiner
    DELEGATED EVENTS


    document

    Click Handler
    $(  document  )
       .on("click",  "a")

    View full-size slide

  25. CONTEXTUAL jQuery Doug Neiner
    DELEGATED EVENTS


    document

    Click Handler
    $(  "#container"  )
       .on("click",  "a")

    View full-size slide

  26. CONTEXTUAL jQuery Doug Neiner
    BOUND VS DELEGATED
    • Separate handler for each
    element
    • Executes only when event
    is triggered on bound
    elements
    • Elements can be retrieved
    ahead of time
    • Must be bound after the
    DOM is ready
    • Single handler for all
    elements
    • Checks event on every
    element in its context, and
    executes when a match is
    found
    • Elements should be retrieved
    at run time
    • Can be setup as soon as the
    context element is ready

    View full-size slide

  27. CONTEXTUAL jQuery Doug Neiner
    TRAVERSAL, FILTERS
    AND SELECTORS

    View full-size slide

  28. CONTEXTUAL jQuery Doug Neiner
    TRAVERSAL METHODS
    • prev
    • prevAll
    • prevUntil
    • next
    • nextAll
    • nextUntil
    • siblings
    • parent
    • parents
    • parentsUntil
    • offsetParent
    • closest
    • children
    • find
    • end

    View full-size slide

  29. CONTEXTUAL jQuery Doug Neiner
    BRITTLE VS FLEXIBLE
    prev
    next
    parent
    children
    prevAll
    nextAll
    closest
    find

    View full-size slide

  30. CONTEXTUAL jQuery Doug Neiner
    WORKING TRAVERSAL
    $(  document  ).on(  "click",  "a.hideTile",  function  (e)  {
       e.preventDefault();
       $(  this  ).parent().hide();
    });

         ...
         Hide
         ...

    View full-size slide

  31. CONTEXTUAL jQuery Doug Neiner
    BROKEN TRAVERSAL
    $(  document  ).on(  "click",  "a.hideTile",  function  (e)  {
       e.preventDefault();
       $(  this  ).parent().hide();
    });

         ...
         Hide
         ...

    View full-size slide

  32. CONTEXTUAL jQuery Doug Neiner
    WORKING TRAVERSAL
    $(  document  ).on(  "click",  "a.hideTile",  function  (e)  {
       e.preventDefault();
       $(  this  ).closest(  ".tile"  ).hide();
    });

         ...
         Hide
         ...

    View full-size slide

  33. CONTEXTUAL jQuery Doug Neiner
    WHICH IS FASTER?
    $(this)
     .closest("form")
     .find(".errors")
     .hide();
    $("#form-­‐errors").hide()

    View full-size slide

  34. CONTEXTUAL jQuery Doug Neiner
    FILTER METHODS
    • filter
    • eq
    • first
    • slice
    • has
    • not

    View full-size slide

  35. CONTEXTUAL jQuery Doug Neiner
    PRO TIP: NOT VS IS
    if(  $(  this  ).not("a")  ){
       alert("Why  does  this  work?");
    }
    if(  $(  this  ).is(":not(a)")  ){
       alert("This  won't  show...  phew!");
    }
    //  or
    if(  !$(  this  ).is("a")  )  {
     alert("This  won't  show  either!");
    }

    View full-size slide

  36. CONTEXTUAL jQuery Doug Neiner
    SELECTORS
    • http://api.jquery.com/category/selectors/
    • A few selectors
    • [name=word],  [name!=word]
    • [name^=word],  [name$=word]
    • .stacked.classes
    • div:has(a)
    • div,  a,  p

    View full-size slide

  37. CONTEXTUAL jQuery Doug Neiner
    WHICH IS FASTER?
    "a[href*=twitter.com]"
    "a.twitter"

    View full-size slide

  38. CONTEXTUAL jQuery Doug Neiner
    WRITE CODE LIKE YOU
    BUY A CAR
    Always weigh the difference
    between cost and quality.

    View full-size slide

  39. CONTEXTUAL jQuery Doug Neiner
    HTML CONVENTIONS

    View full-size slide

  40. CONTEXTUAL jQuery Doug Neiner
    CONVENTIONS ARE PATTERNS
    • You can build them yourself
    • They need to be consistent (or they aren't patterns)
    • They are a promise you make
    • They can change between projects
    • They need to work for you!

    View full-size slide

  41. CONTEXTUAL jQuery Doug Neiner
    KEEP YOUR MARKUP CLEAN

       
           My  song
           My  Author
           
               Preview
               Edit  Song
           
       
       
           My  song
           My  Author
           
               Preview
               Edit  Song
           
       

    View full-size slide

  42. CONTEXTUAL jQuery Doug Neiner
    KEEP YOUR MARKUP CLEAN
    $(  document  ).on("click",  "a[href$=preview],  a[href$=edit]",
       function  (e)  {
           e.preventDefault();
           var  $this  =  $(this),
                   parts  =  $this.attr('href').split('/'),
                   id  =  parts[2],
                   action  =  parts[3],
                   author  =  $this.closest("li").find(".author").html();
           if  (action  ===  "preview")  {
               ...
           }  else  {
               ...
           }
       }
    );

    View full-size slide

  43. CONTEXTUAL jQuery Doug Neiner
    WRITE CODE LIKE YOU
    ASK FOR DIRECTIONS
    Try to get there on your own first!

    View full-size slide

  44. CONTEXTUAL jQuery Doug Neiner
    IN REVIEW
    • Don't spend resources early, strive for just-in-time wherever
    possible.
    • Don't be afraid to use complex selectors in the right settings.
    • Think twice before adding to your markup. See if there is
    another way first.
    • Always write your code with reusability in mind. Think in
    conventions as you work.

    View full-size slide

  45. CONTEXTUAL jQuery Doug Neiner
    @dougneiner
    [email protected]
    http://dougneiner.com
    http://bit.ly/contextual-uk
    TWITTER
    EMAIL
    WEB
    SLIDES

    View full-size slide