Slide 1

Slide 1 text

CONTEXTUAL jQuery Doug Neiner CONTEXTUAL jQuery

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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();    }); });

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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();        }    }); });

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

CONTEXTUAL jQuery Doug Neiner BENEFITS of Contextual jQuery

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

CONTEXTUAL jQuery Doug Neiner IMPLEMENTATION

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

CONTEXTUAL jQuery Doug Neiner HANDLING INITIAL STATE            Sample                  html.no-­‐js  .js,  html.js  .no-­‐js  {  display:  none  }                      document.documentElement.className  =                document.documentElement.className.replace(  "no-­‐js",  "js"  );              
 Something  Amazing!  

Slide 15

Slide 15 text

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  ()  {          …      }); }

Slide 16

Slide 16 text

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"  ); }

Slide 17

Slide 17 text

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.

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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"  );      }); });

Slide 20

Slide 20 text

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();    } });

Slide 21

Slide 21 text

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.

Slide 22

Slide 22 text

CONTEXTUAL jQuery Doug Neiner DELEGATED EVENTS

Slide 23

Slide 23 text

Slide 24

Slide 24 text

Slide 25

Slide 25 text

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

CONTEXTUAL jQuery Doug Neiner TRAVERSAL, FILTERS AND SELECTORS

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Hide

     ...

Slide 32

Slide 32 text

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

Hide

     ...

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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!"); }

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

CONTEXTUAL jQuery Doug Neiner HTML CONVENTIONS

Slide 40

Slide 40 text

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!

Slide 41

Slide 41 text

CONTEXTUAL jQuery Doug Neiner KEEP YOUR MARKUP CLEAN
       
  •        

    My  song

           

    My  Author

                       Preview            Edit  Song            
  •    
  •        

    My  song

           

    My  Author

                       Preview            Edit  Song            

Slide 42

Slide 42 text

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  {            ...        }    } );

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

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.

Slide 45

Slide 45 text

CONTEXTUAL jQuery Doug Neiner @dougneiner doug@dougneiner.com http://dougneiner.com http://bit.ly/contextual-uk TWITTER EMAIL WEB SLIDES