SlideShare a Scribd company logo
1 of 45
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 componentsJarrod Overson
 
An in-depth look at jQuery
An in-depth look at jQueryAn in-depth look at jQuery
An in-depth look at jQueryPaul Bakaus
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)jeresig
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14lrdesign
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQueryGill Cleeren
 
Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkBorisMoore
 
NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05NinjaScript and Mizugumo 2011-02-05
NinjaScript and Mizugumo 2011-02-05lrdesign
 
State of jQuery and Drupal
State of jQuery and DrupalState of jQuery and Drupal
State of jQuery and Drupaljeresig
 
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 .NETJames Johnson
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introductionTomi Juhola
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryGunjan 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 jQueryAnil 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

(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_murrayperspegrity5
 
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 powerpointlbrannan84
 
Curriculum model by nicholls
Curriculum model by nichollsCurriculum model by nicholls
Curriculum model by nichollshiba awan
 
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 DesignYee Bee Choo
 
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 ProcessInternational advisers
 
Developing the curriculum chapter 5
Developing the curriculum chapter 5Developing the curriculum chapter 5
Developing the curriculum chapter 5GrigsbyB
 
Models of curriculum dvelopment
Models of curriculum dvelopmentModels of curriculum dvelopment
Models of curriculum dvelopmentjasleenbrar03
 
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 developmentMamoona 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 CurriculumJonna 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

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 coffeescriptAmir 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 CombinationSean 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
 
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 AngularJSIuliia 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 jQuerycolinbdclark
 
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 DrupalSergey 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 jQuerycolinbdclark
 

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

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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.