SlideShare a Scribd company logo
CONTEXTUAL jQuery




CONTEXTUAL jQuery                       Doug Neiner
CONTEXTUAL jQuery   Doug Neiner
CONTEXTUAL jQuery   Doug Neiner
PRE-OPTIMIZATION
               IS REALLY, REALLY BAD
                    But super easy to get caught up in.




CONTEXTUAL jQuery                                         Doug Neiner
JQUERY CODE STYLES
 • Declarative

 • Dynamic

 • Contextual




CONTEXTUAL jQuery     Doug Neiner
DECLARATIVE
 • Heavy       use of ID’s, some classes, simple selectors

 • 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




CONTEXTUAL jQuery                                                 Doug Neiner
DECLARATIVE

    $(function
()
{
    

var
$container
=
$("#container"),
    





$slider



=
$("#slider"),
    





$footer



=
$("#footer");
    


    

$("#toggle").click(function
()
{
    



$container.toggle();
    

});
    


    

$slider.click(function
()
{
    



$footer.html($slider.html());
    

});
    });

CONTEXTUAL jQuery                         Doug Neiner
DYNAMIC
 • Heavy       use of classes, simple selectors

 • Mixture          of traditional binding and live/delegate binding

 • Less     repeated code

 • Changes          to HTML still may require changes to JS

 • Many       selectors still running on Document Ready




CONTEXTUAL jQuery                                                      Doug Neiner
DYNAMIC

    $(function
()
{
    

var
$container
=
$("#container");
    


    

$("a.toggle").live("click",
function
(e)
{
    



$container.toggle();
    



e.preventDefault();
    

});
    });




CONTEXTUAL jQuery                                  Doug Neiner
CONTEXTUAL
 • Heavy       use of selectors and traversing

 • Minimal          use of ID’s or classes

 • Very      little repeated code

 • HTML    follows a convention so edits
    require less changes to the JS

 • Virtually        no selectors running on Document Ready




CONTEXTUAL jQuery                                            Doug Neiner
CONTEXTUAL

    $("form
a.submit").live("click",
function
(e)
{
    

e.preventDefault();
    

$(this)
    



.closest("form")
    



.find(".errors").slideUp().end()
    



.submit();
    });




CONTEXTUAL jQuery                                     Doug Neiner
BENEFITS
                    of Contextual jQuery




CONTEXTUAL jQuery                          Doug Neiner
BENEFITS
 • Faster      Flexible and More Responsive Code

 • Focussed         Use of Resources

 • Less     code

 • Easier     to maintain

 • Easy     to reuse




CONTEXTUAL jQuery                                  Doug Neiner
IMPLEMENTATION



CONTEXTUAL jQuery                    Doug Neiner
THREE PARTS



                        Live Events
              Traversal, Filters and Selectors
                    HTML Conventions


CONTEXTUAL jQuery                                Doug Neiner
LIVE EVENTS



CONTEXTUAL jQuery                 Doug Neiner
BOUND EVENTS
                        document




   $("a").click(
…
);    <a>              Click Handler




                         <a>              Click Handler



                        <div#container>

CONTEXTUAL jQuery                                         Doug Neiner
LIVE EVENTS
                         document          Click Handler




   $("a")                 <a>
   .live("click",
…
);


                          <a>

                         <div#container>

CONTEXTUAL jQuery                                          Doug Neiner
DELEGATE EVENTS
                      document




   $("#container")     <a>
   .delegate("a",
   


"click",
…
);

                       <a>

                      <div#container>   Click Handler



CONTEXTUAL jQuery                                 Doug Neiner
BIND              VS              LIVE
 • Separate         handler for each   • Single
                                             handler for all
    element                             elements

 • Executes    only when event         • Checksevent on every
    is triggered on bound               element in its context, and
    elements                            executes when a match is
                                        found
 • Elements   can be retrieved
    ahead of time                      • Elements should be
                                        retrieved at run time
 • Mustbe bound after the
    DOM is ready                       • Can   be setup at any time


CONTEXTUAL jQuery                                                 Doug Neiner
WHAT ABOUT INITIALIZATION?
 • Keep      the setup minimal
    •   Use CSS and js/no-js classes
    •   Use selectors or data to determine initialization state

 • Always       opt for just-in-time initialization




CONTEXTUAL jQuery                                                 Doug Neiner
JS/NO-JS
   <!DOCTYPE
html>
   <html
class="no‐js">
   <head>
   


<meta
charset="UTF‐8">
   


<title>Sample</title>
   


<style>
   





html.no‐js
.js,
html.js
.no‐js
{
display:
none
}
   


</style>
   


<script>
   




document.documentElement.className
=

   






document.documentElement.className.replace("no‐js","js");
   


</script>
   </head>
   <body>
   

<div
class="no‐js"><a
href="/about">Learn
About
Us</a></div>
   

<div
class="js">
Something
Amazing!
</div>
   </body>




CONTEXTUAL jQuery                                                     Doug Neiner
DETERMINE INITIALIZATION STATE
   $("a[href^=contact]").live("click",
function
(e)
{
   

e.preventDefault();
   

var
dialog
=
$("#dialog");
   

if(dialog.data("dialog"))
   



dialog.dialog("open");
   

else
   



dialog.dialog();

   });

   $("a[href^=contact]").live("click",
function
(e)
{
   

e.preventDefault();
   

var
dialog
=

   



$(document).data("dialog")
||

   



$(document)
   





.data("dialog",
$("#dialog").dialog({autoOpen:
false}))
   





.data("dialog");
   

dialog.dialog("open");
   });


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.




CONTEXTUAL jQuery                                                Doug Neiner
TRAVERSAL, FILTERS
                     AND SELECTORS



CONTEXTUAL jQuery                        Doug Neiner
TRAVERSAL METHODS
 • prev             • parents

 • prevAll          • parentsUntil

 • prevUntil        • offsetParent

 • next             • closest

 • nextAll          • children

 • nextUntil        • find

 • siblings         • end

 • parent



CONTEXTUAL jQuery                    Doug Neiner
BRITTLE    VS   FLEXIBLE

          prev              prevAll
          next              nextAll
          parent            closest
          children          find


CONTEXTUAL jQuery                     Doug Neiner
WHAT DOES THIS DO?




                    $("a").next("div")




CONTEXTUAL jQuery                        Doug Neiner
TRY THIS INSTEAD




     $("a").nextAll("div:first")




CONTEXTUAL jQuery             Doug Neiner
TRAVERSAL METHODS
 • prev             • parents

 • prevAll          • parentsUntil

 • prevUntil        • offsetParent

 • next             • closest

 • nextAll          • children

 • nextUntil        • find

 • siblings         • end

 • parent



CONTEXTUAL jQuery                    Doug Neiner
WHICH IS FASTER?


   $(this)
   
.closest("form")
   
.nextAll("nav:first")
   
.hide();

   $("#form‐nav").hide()

CONTEXTUAL jQuery           Doug Neiner
FILTER METHODS
 • filter

 • eq

 • first

 • slice

 • has

 • not




CONTEXTUAL jQuery   Doug Neiner
NOT          VS    IS
   if(
$("a").not("a")
){
   

alert("Why
does
this
work?");
   }



   if(
$("a").is(":not(a)")
){
   

alert("This
won't
show...
phew!");
   }

   //
or

   if(
!$("a").is("a")
)
{
   
alert("This
won't
show
either!");
   }




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




CONTEXTUAL jQuery                              Doug Neiner
WHICH IS FASTER?




         $("a[href*=twitter.com]")

                    $("a.twitter")



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




CONTEXTUAL jQuery                                 Doug Neiner
HTML CONVENTIONS



CONTEXTUAL jQuery                 Doug Neiner
SEMANTIC HTML
   <div>
   

<p
class="post‐title">My
Article</p>
   

<p
class="post‐author">Doug
Neiner</p>
   


   

<p>Hi
there!</p>
   

<p
class="post‐quote">My
quote!</p>
   </div>
   



   <div
class="post">
   

<h2>My
Article</h2>
   

<cite>Doug
Neiner</cite>
   


   

<p>Hi
there!</p>
   

<blockquote>My
quote!</blockquote>
   </div>
   






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!




CONTEXTUAL jQuery                                              Doug Neiner
DON'T THINK OF IDS AND
    CLASSES AS YOUR FIRST LINE
           OF ATTACK!


CONTEXTUAL jQuery           Doug Neiner
KEEP YOUR MARKUP CLEAN
   <div
class="record">
   

<h2>My
song</h2>
   

<cite>My
Author</cite>
   

<nav>
   



<a
href="/song/5/preview">Preview</a>
   



<a
href="/song/5/edit">Edit
Song</a>
   

</nav>
   </div>
   <div
class="record">
   

<h2>My
song</h2>
   

<cite>My
Author</cite>
   

<nav>
   



<a
href="/song/12/preview">Preview</a>
   



<a
href="/song/12/edit">Edit
Song</a>
   

</nav>
   </div>




CONTEXTUAL jQuery                               Doug Neiner
EXAMPLE CODE
   $("a[href$=preview],
a[href$=edit]").live("click",
function
(e)
{
   

e.preventDefault();
   

var
$this
=
$(this),
   





parts
=
$this.attr('href').split('/'),
   





id
=
parts[2],
   





action
=
parts[3],
   





author
=
$this.closest("div").find("cite").html();

   

if
(action
===
"preview")
{
   



...
   

}
   });




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




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 IDs or classes to your markup. See
    if there is another way first.

 • Always  write your code with reusability in mind. Think in
    conventions as you work.




CONTEXTUAL jQuery                                                  Doug Neiner
TWITTER   @dougneiner

                      EMAIL   doug@dougneiner.com

                       WEB    http://dougneiner.com




CONTEXTUAL jQuery                                     Doug Neiner

More Related Content

What's hot

JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)
jeresig
 
Real World Web components
Real World Web componentsReal World Web components
Real World Web components
Jarrod Overson
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQuery
Paul Bakaus
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
jeresig
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14
lrdesign
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
Gill Cleeren
 
jQuery
jQueryjQuery
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
BorisMoore
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
Marc Grabanski
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05
lrdesign
 
State of jQuery and Drupal
State of jQuery and DrupalState of jQuery and Drupal
State of jQuery and Drupal
jeresig
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
jeresig
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
jeresig
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
James Johnson
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
Tomi Juhola
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Gunjan Kumar
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
jeresig
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQuery
Anil Kumar
 

What's hot (20)

JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)
 
Real World Web components
Real World Web componentsReal World Web components
Real World Web components
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQuery
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
 
jQuery
jQueryjQuery
jQuery
 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05
 
DirectToWeb 2.0
DirectToWeb 2.0DirectToWeb 2.0
DirectToWeb 2.0
 
State of jQuery and Drupal
State of jQuery and DrupalState of jQuery and Drupal
State of jQuery and Drupal
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Learn css3
Learn css3Learn css3
Learn css3
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQuery
 

Viewers also liked

Telephone
TelephoneTelephone
Telephone
Meidina Putri
 
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
Zaky Luthfi
 
Aied99 a toolstalk_murray
Aied99 a toolstalk_murrayAied99 a toolstalk_murray
Aied99 a toolstalk_murray
perspegrity5
 
Is Implementation The Master Of Curriculum V3
Is Implementation The Master Of Curriculum V3Is Implementation The Master Of Curriculum V3
Is Implementation The Master Of Curriculum V3wtremonti
 
Curriculum evaluation models practical applications for teache
Curriculum evaluation  models   practical applications for teacheCurriculum evaluation  models   practical applications for teache
Curriculum evaluation models practical applications for teacheBELETE DAMTEW
 
Curriculum leadership chapter 5 powerpoint
Curriculum leadership chapter 5   powerpointCurriculum leadership chapter 5   powerpoint
Curriculum leadership chapter 5 powerpoint
lbrannan84
 
Evaluation model
Evaluation modelEvaluation model
Evaluation model
Aileen Banaguas
 
Curriculum model by nicholls
Curriculum model by nichollsCurriculum model by nicholls
Curriculum model by nicholls
hiba awan
 
Contextual Theology
Contextual TheologyContextual Theology
Contextual Theology
Robert Munson
 
TSL3143 Topic 2a Models of Curriculum Design
TSL3143 Topic 2a Models of Curriculum DesignTSL3143 Topic 2a Models of Curriculum Design
TSL3143 Topic 2a Models of Curriculum Design
Yee Bee Choo
 
Decker Walker's curriculum model (1971)
Decker Walker's curriculum model (1971)Decker Walker's curriculum model (1971)
Decker Walker's curriculum model (1971)
Resa R. Noel PhD., MPhil., B.A., DipEd
 
Discourse analysis (Linguistics Forms and Functions)
Discourse analysis (Linguistics Forms and Functions)Discourse analysis (Linguistics Forms and Functions)
Discourse analysis (Linguistics Forms and Functions)
Satya Permadi
 
WHEELER Cyclical Model of curriculum Process
WHEELER Cyclical Model of curriculum ProcessWHEELER Cyclical Model of curriculum Process
WHEELER Cyclical Model of curriculum Process
International advisers
 
Developing the curriculum chapter 5
Developing the curriculum chapter 5Developing the curriculum chapter 5
Developing the curriculum chapter 5GrigsbyB
 
Curriculum and instruction day 3
Curriculum  and instruction day 3Curriculum  and instruction day 3
Curriculum and instruction day 3
Hamdard University Karachi
 
Models of curriculum dvelopment
Models of curriculum dvelopmentModels of curriculum dvelopment
Models of curriculum dvelopment
jasleenbrar03
 
Curriculum models
Curriculum modelsCurriculum models
Curriculum modelsKt Mosinyi
 
Cyclical models of curriculum development
Cyclical models of curriculum developmentCyclical models of curriculum development
Cyclical models of curriculum development
Mamoona Shahzad
 
curriculum design and models
curriculum design and models curriculum design and models
curriculum design and models
gaestimos
 
Linear model of Curriculum
Linear model of CurriculumLinear model of Curriculum
Linear model of Curriculum
Jonna May Berci
 

Viewers also liked (20)

Telephone
TelephoneTelephone
Telephone
 
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
(Civic and political education 2) murray print, dirk lange (auth.), murray pr...
 
Aied99 a toolstalk_murray
Aied99 a toolstalk_murrayAied99 a toolstalk_murray
Aied99 a toolstalk_murray
 
Is Implementation The Master Of Curriculum V3
Is Implementation The Master Of Curriculum V3Is Implementation The Master Of Curriculum V3
Is Implementation The Master Of Curriculum V3
 
Curriculum evaluation models practical applications for teache
Curriculum evaluation  models   practical applications for teacheCurriculum evaluation  models   practical applications for teache
Curriculum evaluation models practical applications for teache
 
Curriculum leadership chapter 5 powerpoint
Curriculum leadership chapter 5   powerpointCurriculum leadership chapter 5   powerpoint
Curriculum leadership chapter 5 powerpoint
 
Evaluation model
Evaluation modelEvaluation model
Evaluation model
 
Curriculum model by nicholls
Curriculum model by nichollsCurriculum model by nicholls
Curriculum model by nicholls
 
Contextual Theology
Contextual TheologyContextual Theology
Contextual Theology
 
TSL3143 Topic 2a Models of Curriculum Design
TSL3143 Topic 2a Models of Curriculum DesignTSL3143 Topic 2a Models of Curriculum Design
TSL3143 Topic 2a Models of Curriculum Design
 
Decker Walker's curriculum model (1971)
Decker Walker's curriculum model (1971)Decker Walker's curriculum model (1971)
Decker Walker's curriculum model (1971)
 
Discourse analysis (Linguistics Forms and Functions)
Discourse analysis (Linguistics Forms and Functions)Discourse analysis (Linguistics Forms and Functions)
Discourse analysis (Linguistics Forms and Functions)
 
WHEELER Cyclical Model of curriculum Process
WHEELER Cyclical Model of curriculum ProcessWHEELER Cyclical Model of curriculum Process
WHEELER Cyclical Model of curriculum Process
 
Developing the curriculum chapter 5
Developing the curriculum chapter 5Developing the curriculum chapter 5
Developing the curriculum chapter 5
 
Curriculum and instruction day 3
Curriculum  and instruction day 3Curriculum  and instruction day 3
Curriculum and instruction day 3
 
Models of curriculum dvelopment
Models of curriculum dvelopmentModels of curriculum dvelopment
Models of curriculum dvelopment
 
Curriculum models
Curriculum modelsCurriculum models
Curriculum models
 
Cyclical models of curriculum development
Cyclical models of curriculum developmentCyclical models of curriculum development
Cyclical models of curriculum development
 
curriculum design and models
curriculum design and models curriculum design and models
curriculum design and models
 
Linear model of Curriculum
Linear model of CurriculumLinear model of Curriculum
Linear model of Curriculum
 

Similar to Contextual jQuery

Jquery
JqueryJquery
Jquery
Zoya Shaikh
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
Amir Barylko
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
RTigger
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
Doris Chen
 
Web2.0 with jQuery in English
Web2.0 with jQuery in EnglishWeb2.0 with jQuery in English
Web2.0 with jQuery in English
Lau Bech Lauritzen
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
Thinqloud
 
J query presentation
J query presentationJ query presentation
J query presentationakanksha17
 
J query presentation
J query presentationJ query presentation
J query presentationsawarkar17
 
Quick start with AngularJS
Quick start with AngularJSQuick start with AngularJS
Quick start with AngularJS
Iuliia Baranova
 
Jquery introduce
Jquery introduceJquery introduce
Jquery introduceMajor Ye
 
Creating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUICreating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUIGonzalo Cordero
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
colinbdclark
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)David Giard
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
Sergey Semashko
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
colinbdclark
 

Similar to Contextual jQuery (20)

Jquery
JqueryJquery
Jquery
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Web2.0 with jQuery in English
Web2.0 with jQuery in EnglishWeb2.0 with jQuery in English
Web2.0 with jQuery in English
 
bcgr3-jquery
bcgr3-jquerybcgr3-jquery
bcgr3-jquery
 
bcgr3-jquery
bcgr3-jquerybcgr3-jquery
bcgr3-jquery
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
J query presentation
J query presentationJ query presentation
J query presentation
 
J query presentation
J query presentationJ query presentation
J query presentation
 
JQuery
JQueryJQuery
JQuery
 
JQuery
JQueryJQuery
JQuery
 
Quick start with AngularJS
Quick start with AngularJSQuick start with AngularJS
Quick start with AngularJS
 
Jquery introduce
Jquery introduceJquery introduce
Jquery introduce
 
Creating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUICreating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUI
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
QADay
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Breaking the Ruby Performance Barrier with YJIT
Breaking the Ruby Performance Barrier with YJITBreaking the Ruby Performance Barrier with YJIT
Breaking the Ruby Performance Barrier with YJIT
maximechevalierboisv1
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Breaking the Ruby Performance Barrier with YJIT
Breaking the Ruby Performance Barrier with YJITBreaking the Ruby Performance Barrier with YJIT
Breaking the Ruby Performance Barrier with YJIT
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 

Contextual jQuery

  • 2. CONTEXTUAL jQuery Doug Neiner
  • 3. CONTEXTUAL jQuery Doug Neiner
  • 4. PRE-OPTIMIZATION IS REALLY, REALLY BAD But super easy to get caught up in. CONTEXTUAL jQuery Doug Neiner
  • 5. JQUERY CODE STYLES • Declarative • Dynamic • Contextual CONTEXTUAL jQuery Doug Neiner
  • 6. DECLARATIVE • Heavy use of ID’s, some classes, simple selectors • 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 CONTEXTUAL jQuery Doug Neiner
  • 7. DECLARATIVE $(function
()
{ 

var
$container
=
$("#container"), 





$slider



=
$("#slider"), 





$footer



=
$("#footer"); 

 

$("#toggle").click(function
()
{ 



$container.toggle(); 

}); 

 

$slider.click(function
()
{ 



$footer.html($slider.html()); 

}); }); CONTEXTUAL jQuery Doug Neiner
  • 8. DYNAMIC • Heavy use of classes, simple selectors • Mixture of traditional binding and live/delegate binding • Less repeated code • Changes to HTML still may require changes to JS • Many selectors still running on Document Ready CONTEXTUAL jQuery Doug Neiner
  • 9. DYNAMIC $(function
()
{ 

var
$container
=
$("#container"); 

 

$("a.toggle").live("click",
function
(e)
{ 



$container.toggle(); 



e.preventDefault(); 

}); }); CONTEXTUAL jQuery Doug Neiner
  • 10. CONTEXTUAL • Heavy use of selectors and traversing • Minimal use of ID’s or classes • Very little repeated code • HTML follows a convention so edits require less changes to the JS • Virtually no selectors running on Document Ready CONTEXTUAL jQuery Doug Neiner
  • 11. CONTEXTUAL $("form
a.submit").live("click",
function
(e)
{ 

e.preventDefault(); 

$(this) 



.closest("form") 



.find(".errors").slideUp().end() 



.submit(); }); CONTEXTUAL jQuery Doug Neiner
  • 12. BENEFITS of Contextual jQuery CONTEXTUAL jQuery Doug Neiner
  • 13. BENEFITS • Faster Flexible and More Responsive Code • Focussed Use of Resources • Less code • Easier to maintain • Easy to reuse CONTEXTUAL jQuery Doug Neiner
  • 15. THREE PARTS Live Events Traversal, Filters and Selectors HTML Conventions CONTEXTUAL jQuery Doug Neiner
  • 17. BOUND EVENTS document $("a").click(
…
); <a> Click Handler <a> Click Handler <div#container> CONTEXTUAL jQuery Doug Neiner
  • 18. LIVE EVENTS document Click Handler $("a") <a> .live("click",
…
); <a> <div#container> CONTEXTUAL jQuery Doug Neiner
  • 19. DELEGATE EVENTS document $("#container") <a> .delegate("a", 


"click",
…
); <a> <div#container> Click Handler CONTEXTUAL jQuery Doug Neiner
  • 20. BIND VS LIVE • Separate handler for each • Single handler for all element elements • Executes only when event • Checksevent on every is triggered on bound element in its context, and elements executes when a match is found • Elements can be retrieved ahead of time • Elements should be retrieved at run time • Mustbe bound after the DOM is ready • Can be setup at any time CONTEXTUAL jQuery Doug Neiner
  • 21. WHAT ABOUT INITIALIZATION? • Keep the setup minimal • Use CSS and js/no-js classes • Use selectors or data to determine initialization state • Always opt for just-in-time initialization CONTEXTUAL jQuery Doug Neiner
  • 22. JS/NO-JS <!DOCTYPE
html> <html
class="no‐js"> <head> 


<meta
charset="UTF‐8"> 


<title>Sample</title> 


<style> 





html.no‐js
.js,
html.js
.no‐js
{
display:
none
} 


</style> 


<script> 




document.documentElement.className
=
 






document.documentElement.className.replace("no‐js","js"); 


</script> </head> <body> 

<div
class="no‐js"><a
href="/about">Learn
About
Us</a></div> 

<div
class="js">
Something
Amazing!
</div> </body> CONTEXTUAL jQuery Doug Neiner
  • 23. DETERMINE INITIALIZATION STATE $("a[href^=contact]").live("click",
function
(e)
{ 

e.preventDefault(); 

var
dialog
=
$("#dialog"); 

if(dialog.data("dialog")) 



dialog.dialog("open"); 

else 



dialog.dialog();
 }); $("a[href^=contact]").live("click",
function
(e)
{ 

e.preventDefault(); 

var
dialog
=
 



$(document).data("dialog")
||
 



$(document) 





.data("dialog",
$("#dialog").dialog({autoOpen:
false})) 





.data("dialog"); 

dialog.dialog("open"); }); CONTEXTUAL jQuery Doug Neiner
  • 24. 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. CONTEXTUAL jQuery Doug Neiner
  • 25. TRAVERSAL, FILTERS AND SELECTORS CONTEXTUAL jQuery Doug Neiner
  • 26. TRAVERSAL METHODS • prev • parents • prevAll • parentsUntil • prevUntil • offsetParent • next • closest • nextAll • children • nextUntil • find • siblings • end • parent CONTEXTUAL jQuery Doug Neiner
  • 27. BRITTLE VS FLEXIBLE prev prevAll next nextAll parent closest children find CONTEXTUAL jQuery Doug Neiner
  • 28. WHAT DOES THIS DO? $("a").next("div") CONTEXTUAL jQuery Doug Neiner
  • 29. TRY THIS INSTEAD $("a").nextAll("div:first") CONTEXTUAL jQuery Doug Neiner
  • 30. TRAVERSAL METHODS • prev • parents • prevAll • parentsUntil • prevUntil • offsetParent • next • closest • nextAll • children • nextUntil • find • siblings • end • parent CONTEXTUAL jQuery Doug Neiner
  • 31. WHICH IS FASTER? $(this) 
.closest("form") 
.nextAll("nav:first") 
.hide(); $("#form‐nav").hide() CONTEXTUAL jQuery Doug Neiner
  • 32. FILTER METHODS • filter • eq • first • slice • has • not CONTEXTUAL jQuery Doug Neiner
  • 33. NOT VS IS if(
$("a").not("a")
){ 

alert("Why
does
this
work?"); } if(
$("a").is(":not(a)")
){ 

alert("This
won't
show...
phew!"); } //
or if(
!$("a").is("a")
)
{ 
alert("This
won't
show
either!"); } CONTEXTUAL jQuery Doug Neiner
  • 34. 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 CONTEXTUAL jQuery Doug Neiner
  • 35. WHICH IS FASTER? $("a[href*=twitter.com]") $("a.twitter") CONTEXTUAL jQuery Doug Neiner
  • 36. WRITE CODE LIKE YOU BUY A CAR Always weigh the difference between cost and quality. CONTEXTUAL jQuery Doug Neiner
  • 38. SEMANTIC HTML <div> 

<p
class="post‐title">My
Article</p> 

<p
class="post‐author">Doug
Neiner</p> 

 

<p>Hi
there!</p> 

<p
class="post‐quote">My
quote!</p> </div> 

 <div
class="post"> 

<h2>My
Article</h2> 

<cite>Doug
Neiner</cite> 

 

<p>Hi
there!</p> 

<blockquote>My
quote!</blockquote> </div> 

 CONTEXTUAL jQuery Doug Neiner
  • 39. 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! CONTEXTUAL jQuery Doug Neiner
  • 40. DON'T THINK OF IDS AND CLASSES AS YOUR FIRST LINE OF ATTACK! CONTEXTUAL jQuery Doug Neiner
  • 41. KEEP YOUR MARKUP CLEAN <div
class="record"> 

<h2>My
song</h2> 

<cite>My
Author</cite> 

<nav> 



<a
href="/song/5/preview">Preview</a> 



<a
href="/song/5/edit">Edit
Song</a> 

</nav> </div> <div
class="record"> 

<h2>My
song</h2> 

<cite>My
Author</cite> 

<nav> 



<a
href="/song/12/preview">Preview</a> 



<a
href="/song/12/edit">Edit
Song</a> 

</nav> </div> CONTEXTUAL jQuery Doug Neiner
  • 42. EXAMPLE CODE $("a[href$=preview],
a[href$=edit]").live("click",
function
(e)
{ 

e.preventDefault(); 

var
$this
=
$(this), 





parts
=
$this.attr('href').split('/'), 





id
=
parts[2], 





action
=
parts[3], 





author
=
$this.closest("div").find("cite").html(); 

if
(action
===
"preview")
{ 



... 

} }); CONTEXTUAL jQuery Doug Neiner
  • 43. WRITE CODE LIKE YOU ASK FOR DIRECTIONS Try to get there on your own first! CONTEXTUAL jQuery Doug Neiner
  • 44. 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 IDs or classes to your markup. See if there is another way first. • Always write your code with reusability in mind. Think in conventions as you work. CONTEXTUAL jQuery Doug Neiner
  • 45. TWITTER @dougneiner EMAIL doug@dougneiner.com WEB http://dougneiner.com CONTEXTUAL jQuery Doug Neiner

Editor's Notes

  1. 1) bind before DOM ready, events captured quickly 2) Purchase tickets to every conference in 2011 just in case you attend 3) Follow a convention to reduce your code. Why reconfigure code all the time.