points & badgesHow does this work?flight timevideo lessonschallenges3:00
points & badges
In order to learn jQuery you need to know:☑☑HTMLCSSJavaScriptcontentstylebehavior
1level
What is jQuery?
What you can do with jQuery1.1 What is jQuery?reveal interface elements
What you can do with jQuery1.1 What is jQuery?change content based on user actions
What you can do with jQuery1.1 What is jQuery?toggle CSS classes to highlight an element
talkanimatelistenchangefindjQuery makes it easy to:1.1 What is jQuery?elements in an HTML documentHTML contentto what a use...
HTML documentChanging contentHow can we modify the textof the <h1> element?1.1 What is jQuery?<!DOCTYPE html><html><head><...
HTML documentFinding the proper HTMLHow can we searchthrough our html?We need to understand how our browserorganizes the H...
Document Object ModelA tree-like structure created by browsers so we canquickly find HTML Elements using JavaScript.1.1 Wha...
Loading HTML into the DOMDOMbrowser1.1 What is jQuery?HTML document100%0% 50%<!DOCTYPE html><html><head><title>jQuery Adve...
htmlheadbodytitleh1pjQuery Adven...element textnode types:The DOMDOCUMENTWhere do...Plan your...Inside the DOM, HTML eleme...
htmlheadbodytitleh1pjQuery Adven...element textnode types:The DOMDOCUMENTWhere do...Plan your...How do we search through t...
JavaScriptHow do we find things using the DOM?1.1 What is jQuery?HTMLWeb ServerRequests a WebpageSends the HTMLHTMLJavaScri...
DOMDOMDOMDOMDOMJavaScripteach browser has a slightlydifferent DOM interfaceOf course, there’s a catch1.1 What is jQuery?
DOMIf our JavaScript uses jQuery to interactwith the DOM then it will work on mostmodern browsers.DOMDOMDOMDOMjQuery to th...
Basic jQuery usagethis is the jQuery function1.1 What is jQuery?jQuery(<code>);JavaScript
How jQuery Accesses The DOM1.1 What is jQuery?jQuery(document);The DOMBut how can we search through the DOM?JavaScript
h1 { font-size: 3em; }CSS selectorsp { color: blue; }1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventure...
Using the jQuery function to find nodesjQuery("h1");jQuery("p");1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery...
Changing the content of an element<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you...
Selecting by HTML element namehtmlheadbodytitleh1pjQuery Adv...DOM representation of the documentDOCUMENTWhere do...Plan y...
Selecting by HTML element name$("h1")htmlheadbodytitleh1h1pjQuery Adv...DOM representation of the documentDOCUMENTWhere do...
"Where do you want to go"Fetching an element’s text1.1 What is jQuery?htmlheadbodytitleh1pjQuery Adv...DOM representation ...
Modifying an element’s texthtmlheadbodytitleh1pjQuery Adv...DOM representation of the documentDOCUMENTWhere to?Plan your.....
DOMJavaScript may execute before the DOM loadsHTML1.1 What is jQuery?100%0% 50%$("h1").text( );"Where to?"We need to make ...
DOM“I’m ready!”Listen for “I’m ready” then run <code>The DOM ready eventHTML1.1 What is jQuery?100%0% 50%How can we listen...
DOM“I’m ready!”Listening for document ready1.1 What is jQuery?jQuery(document).ready(function(){});Will only run this code...
Our completed code1.1 What is jQuery?jQuery(document).ready(function(){});$("h1").text("Where to?");
Using jQuery
Getting started<script src="jquery.min.js"></script><script src="application.js"></script>1.2 Using jQuerydownload jQueryl...
find themmodify their textChanging multiple elements at onceHTML documentHow do we change the text ofevery <li> in this pag...
Load HTML into the DOMHTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want to go?</h1><h2>Tra...
Selecting multiple elements$("li")HTML documentbodyh1lililih2Where do...Plan your...1.2 Using jQueryulRomeliParisliRioli;<...
Modifying each of their text nodesHTML documentbodyh1h2Where do...Plan your...1.2 Using jQueryullilili.text("Orlando");$("...
We can find elements by ID or Classp { ... }#container { ... }.articles { ... }$("p");$("#container");$(".articles");1.2 Us...
find it using the IDChanging multiple elements at onceHTML documentHow do we specifically select the <ul>that has a “destina...
Selecting by unique ID$("#destinations");HTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want...
find it using the classChanging multiple elements at onceHTML documentHow can we select just the <li> thathas a “promo” cla...
Selecting by Class Name$(".promo");HTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want to go...
2level
Searching the DOM
2.1 Searching the DOMSelecting descendantsHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Pla...
lilili<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><...
<li>Paris</li><li>Rome</li><li class=promo>Rio</li><h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan yo...
ulliliParislililililiSelecting direct children$("#destinations li");HTML documentbodyulRomeRioli2.1 Searching the DOM...we...
How do we find only the <li> elements that aredirect children of the “destinations” <ul> then?child selectorSelecting only ...
liliParisullilililibodyulRomeRioli...Selecting only direct children$("#destinations > li");HTML documentthe sign matterspa...
How do we find only elementswith either a “promo” class or a “france” IDmultiple selectorSelecting multiple elementsHTML do...
ulliliulSelecting multiple elements$(".promo, #france");HTML document<h1>Where do you want to go?</h1><h2>Travel Destinati...
lilililibodyh1h2Where do...Plan your...ulRomeParisliRio$("#destinations li:first");CSS-like pseudo classesfilter$("#destina...
lilibodyh1h2Where do...Plan your...ulRomeParisliRioliCSS-like pseudo classes$("#destinations li:odd");$("#destinations li:...
Traversing
2.2 TraversingWalking the DOM by traversing itHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p...
lilililililiFiltering by traversing$("#destinations li");$("#destinations").find("li");It takes a bit more code, but it’s ...
liliFiltering by traversing$("li:first");$("li").first();bodyh1h2Where do...Plan your...ulRomeParisliRioli2.2 Traversing
liliFiltering by traversing$("li:last");$("li").last();bodyh1h2Where do...Plan your...ulRomeliParisliRio2.2 Traversing
HTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinat...
lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeParisliRioliWalking the DOM2.2 Traversing
lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisRioli$("li").first().next();Walking the DOMli2.2 Traversing
lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisRioli$("li").first().next();$("li").first().next().prev()...
HTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinat...
lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeParisliRioliWalking up the DOM2.2 Traversing
ul$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisliRioli$("li").first().parent();Walking up the DOMli2.2 Tra...
Walking down the DOMHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure....
Walking the DOM up and down$("#destinations").children("li");children(), unlike find(), only selects direct childrenulliliP...
3level
Working with the DOM
3.1 Manipulating the DOM
remove a DOM nodeliDOM representation of the documentDOCUMENTHawaiian Vac...h2Get Pricebuttonp$399.99Appending to the DOMc...
application.jsAppending to the DOMDOCUMENTh2Get Pricebuttonp$399.99livar price = $(<p>From $399.99</p>);var price = "From ...
DOCUMENTh2Get Pricebuttonliapplication.js.append(<element>).after(<element>) .before(<element>).prepend(<element>)Appendin...
DOCUMENTh2Get PricebuttonliBeforeapplication.js$(.vacation).before(price);$(document).ready(function() {var price = $(<p>F...
liDOCUMENTh2Get Pricebuttonp$399.99Afterapplication.js$(#vacation).before(price);Puts the price node after .vacation$(docu...
var price = $(<p>From $399.99</p>);$(.vacation).prepend(price);application.jsAdds the node to the top of .vacation$(docume...
application.js3.1 Manipulating the DOMPrepend and AppendPuts the price node at the bottom of .vacation$(.vacation).append(...
application.js$(document).ready(function() {3.1 Manipulating the DOMRemoving from the DOMRemoves the <button> from the DOM...
3.1 Manipulating the DOM
DOCUMENTh2Get Pricebuttonli.appendTo(<element>).insertAfter(<element>) .insertBefore(<element>).prependTo(<element>)Append...
Acting on Interaction
$(document).ready(<event handler function>);Passing in a functionfunction() {// executing the function runs the code// bet...
3.2 Acting on Interaction
application.jsWatching for ClickDOCUMENTHawaiian Vacationh2Get Pricebuttonli class="vacation"Target all buttonsWatch for a...
application.jsRemoving from the DOMDOCUMENTHawaiian Vacationh2Get Pricebuttonliruns when the DOM is readyruns when a butto...
application.jsRemoving from the DOM3.2 Acting on Interactionvar price = $(<p>From $399.99</p>);$(.vacation).append(price);...
Now the price will be shown when we click the button
Refactor using Traversing
What if there are multiple vacation packages?
$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(.vacation).append(price...
$(this).remove();An Introduction to $(this)application.jsulDOCUMENTlibuttonplibuttonpdivIf clicked, the button will be ‘th...
application.jsAn Introduction to $(this)3.3 Refactor Using TraversingulDOCUMENTlibuttonplibuttonpdivOnly removes whichever...
The clicked button will now be removed
application.jsAdds the <p> node after the <button>Traversing from $(this)ulDOCUMENTHawaiian Vac...lih2Get Pricebuttonp$399...
application.jsTraversing from $(this)3.3 Refactor Using TraversingAdd the price as a sibling after buttonulDOCUMENTHawaiia...
application.jsWhat if the button is moved?ulDOCUMENTHawaiian Vac...lih2Get Pricebuttonp$399.993.3 Refactor Using Traversin...
application.jsUsing .closest(<selector>)3.3 Refactor Using TraversingulDOCUMENTHawaiian Vac...lih2Get Pricebuttondiv$(this...
application.js$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).rem...
The prices will be added at the right place
Traversing and Filtering
How do we allow vacations to have different prices?
<li class="vacation onsale"<h3>Hawaiian Vacation</h3><button>Get Price</button><ul class=comments><li>Amazing deal!</li><l...
var amount = $(this).closest(.vacation).data(price);application.jsReads from the data-price attributeJoins two strings to ...
application.jsRefactoring ‘Get Price’$(document).ready(function() {$(button).on(click, function() {$(this).closest(.vacati...
var amount = $(this).closest(.vacation).data(price);$(this).closest(.vacation).append(price);application.jsReusing jQuery ...
vacation.append(price);var amount = vacation.data(price);application.jsReusing jQuery Objectsvar vacation = $(this).closes...
Each vacation can have its dynamic own price now
application.js$(.vacation).on(click, button, function() {});If we add new buttons anywhere, they will trigger this click h...
We’ll implement our new filters next
<div id=filters>...<button class=onsale-filter>On Sale Now</button><button class=expiring-filter>Expiring</button>...</div...
application.jsFiltering for Vacations On saledivDOCUMENTbutton class="onsale-filter"button class="expiring-filter"// find ...
Filtering for Vacations On saleulDOCUMENTliullililiclass="vacation onsale"class="vacation"class="vacation"class="comments"...
Class Manipulationapplication.jsFiltering for Vacations On sale$(.vacation).filter(.onsale).addClass(highlighted);.addClas...
application.jsFiltering for Vacations On saleFinds only the right vacations Adds a class of ‘highlighted’The same can be d...
How do we make sure not all vacations are highlighted?
application.jsUnhighlighting Vacations$(#filters).on(click, .onsale-filter, function() {$(.vacation).filter(.onsale).addCl...
We clear the highlighted class on click, onlyhighlighting the targeted vacations
4level
On DOM Load
4.1 On DOM Load
.ticket {display: none;}index.htmlHide ticket on page loadAdding Ticket Confirmationfind the ticketshow the ticketwatch for ...
application.js$(.confirmation).on(click, button, function() {});Using slideDown to Show Elementsindex.htmljQuery Object Me...
Why doesn’t the button work?
alert(Hello);Alert and Length4.1 On DOM Load$(li).length;3To query how many nodes are on a page.
$(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});application.jsa...
application.js$(document).ready(function() {});The button is found after the DOM has loadedWe Forgot $(document).ready() a...
Now that the DOM has loaded, jQuery can find our button
Expanding on on()
What if we also want to show the ticket when theyhover over the <h3> tag?
application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation)....
application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation)....
We have two ways of showing the ticket now
application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation)....
application.js$(document).ready(function() {$(.confirmation).on(click, button, showTicket);$(.confirmation).on(mouseenter,...
Now the exact same code is run for both events
Keyboard Events
Changing this “Tickets” input field should recalculate the total
<div class="vacation" data-price=399.99><h3>Hawaiian Vacation</h3><p>$399.99 per ticket</p><p>Tickets:<input type=number c...
Keyboard Events Form Events$(document).ready(function() {$(.vacation).on(?, .quantity, function() {});});application.jshtt...
$(document).ready(function() {$(.vacation).on(keyup, .quantity, function() {});});application.jsWriting our Event HandlerD...
application.jsGetting the Quantity of TicketsDOCUMENTli .vacationspanpinput .quantityp#totaljQuery Object Methods.val().va...
application.jsSetting the Total PriceDOCUMENTli .vacationspanpinput .quantityp#totalYou can pass a number or a string to t...
application.jsThe Completed Event HandlerDOCUMENTli .vacationspanpinput .quantityp#totalWhenever the quantity is changed, ...
The total changesimmediately as we wanted
Link Layover
Clicking Show Comments will cause them to fade in
Clicking this link...Preparing for FlightulDOCUMENTShow Commentslialiulli...will show the comments.vacation.expand.comment...
Preparing for FlightulDOCUMENTShow Commentslialiulli.vacation.expand.commentsFind the .comments ul using traversing$(this)...
jQuery Object MethodsPreparing for Flight.fadeToggle().fadeIn() .fadeOut()These are similar to the slide methods$(document...
$(document).ready(function() {$(.vacation).on(click, .expand, function() {$(this).closest(.vacation).find(.comments)});});...
Why does the page jump to the top?
<a href=# class=expand>Show Comments</a>index.htmlHow the Browser Handles the ClickulDOCUMENTShow Commentslialiulli.vacati...
});The Event ObjectAdd the event parameterapplication.jsDOM TREEulDOCUMENTShow Commentslialiulli.vacation.expand.comments$...
event.stopPropagation()DOM TREEulDOCUMENTShow Commentslialiulli.vacation.expand.commentsThe browser will still handle the ...
$(document).ready(function() {$(.vacation).on(click, .expand,function(event) {$(this).closest(.vacation).find(.comments).f...
We’re preventing the default action of the browser now.
5level
Taming CSS
HTMLCSSJavaScriptcontentstylebehaviorSeparation of Concerns5.1 Taming CSSTo style something based on userinteraction, whic...
5.1 Taming CSSulDOM representationDOCUMENTli .vacationdiv #vacations...and allow people to clickon the <li> elementChangin...
5.1 Taming CSSapplication.jsChanging the Style$(this).css(background-color, #252b30).css(border-color, 1px solid #967);$(t...
5.1 Taming CSSShowing the PriceulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.jsjQuery Object Methods....
5.1 Taming CSSShowing the PriceulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js.priceHighlights the V...
Our .vacation elements are highlighted when we click on them
5.1 Taming CSSMoving Styles to External CSSulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js});});.pri...
5.1 Taming CSSMoving Styles to External CSSapplication.js});});It’s now much easier to manipulate with external CSS styles...
5.1 Taming CSSMoving Styles to External CSSulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js$(document...
Our refactored page still works, and will be much easier to maintain
Challenges5.1 Taming CSS
Animation
What can we do to add a bit more movement to this?
Takes in a JavaScript objectsimilar to the .css() methodAdding MovementjQuery Object Methods.animate(<object>)ulDOM repres...
Adding MovementulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsWill adjust a CSS property pixe...
Our animation can slide up but not slide down
Moving Back DownulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsHow do we set ‘top’ to ‘0px’ i...
Moving Back DownulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsjQuery Object Methods.hasClass...
Moving Back Downapplication.jsOur vacation package will move up and down5.2 AnimationulDOM representationDOCUMENTli .vacat...
Could we speed this up a little? Our customers don’t have all day.
Changing the Speed$(this).animate({top: -10px});$(this).animate({top: -10px}, 400);We can optionally pass in the speed as ...
$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);if($(this).h...
Our jQuery animation is now using a ‘fast’ speed
The Next Step with CSS AnimationsulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsif($(this).ha...
Animation Durationapplication.js5.2 Animationtransition: top 0.2s;}.highlighted {top: -10px;}Will only work with browsers ...
Working with Modern Browsers5.2 Animationapplication.css-moz-transition: top 0.2s;-o-transition: top 0.2s;-webkit-transiti...
CSS Animations are a huge topic, but worth looking into
Learning Jquery
Upcoming SlideShare
Loading in …5
×

Learning Jquery

475 views

Published on

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
475
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
16
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Learning Jquery

  1. 1. points & badgesHow does this work?flight timevideo lessonschallenges3:00
  2. 2. points & badges
  3. 3. In order to learn jQuery you need to know:☑☑HTMLCSSJavaScriptcontentstylebehavior
  4. 4. 1level
  5. 5. What is jQuery?
  6. 6. What you can do with jQuery1.1 What is jQuery?reveal interface elements
  7. 7. What you can do with jQuery1.1 What is jQuery?change content based on user actions
  8. 8. What you can do with jQuery1.1 What is jQuery?toggle CSS classes to highlight an element
  9. 9. talkanimatelistenchangefindjQuery makes it easy to:1.1 What is jQuery?elements in an HTML documentHTML contentto what a user does and react accordinglycontent on the pageover the network to fetch new content
  10. 10. HTML documentChanging contentHow can we modify the textof the <h1> element?1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>find itchange it
  11. 11. HTML documentFinding the proper HTMLHow can we searchthrough our html?We need to understand how our browserorganizes the HTML it receives.1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>find it
  12. 12. Document Object ModelA tree-like structure created by browsers so we canquickly find HTML Elements using JavaScript.1.1 What is jQuery?“DOM”
  13. 13. Loading HTML into the DOMDOMbrowser1.1 What is jQuery?HTML document100%0% 50%<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>
  14. 14. htmlheadbodytitleh1pjQuery Adven...element textnode types:The DOMDOCUMENTWhere do...Plan your...Inside the DOM, HTML elements become “nodes”which have relationships with one another.What does that DOM structure look like?1.1 What is jQuery?HTML document<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>
  15. 15. htmlheadbodytitleh1pjQuery Adven...element textnode types:The DOMDOCUMENTWhere do...Plan your...How do we search through the DOM?1.1 What is jQuery?JavaScriptJavaScript gives developers alanguage to interact with the DOM.
  16. 16. JavaScriptHow do we find things using the DOM?1.1 What is jQuery?HTMLWeb ServerRequests a WebpageSends the HTMLHTMLJavaScript+ other files neededto load that pageDOMLoads intoInteracts withWeb Browser
  17. 17. DOMDOMDOMDOMDOMJavaScripteach browser has a slightlydifferent DOM interfaceOf course, there’s a catch1.1 What is jQuery?
  18. 18. DOMIf our JavaScript uses jQuery to interactwith the DOM then it will work on mostmodern browsers.DOMDOMDOMDOMjQuery to the rescue!1.1 What is jQuery?JavaScript
  19. 19. Basic jQuery usagethis is the jQuery function1.1 What is jQuery?jQuery(<code>);JavaScript
  20. 20. How jQuery Accesses The DOM1.1 What is jQuery?jQuery(document);The DOMBut how can we search through the DOM?JavaScript
  21. 21. h1 { font-size: 3em; }CSS selectorsp { color: blue; }1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>HTML documentWe need to use CSS selectors
  22. 22. Using the jQuery function to find nodesjQuery("h1");jQuery("p");1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>HTML document jQuery selectors$("h1");$("p");= short & sweetsyntax
  23. 23. Changing the content of an element<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>HTML document1.1 What is jQuery?How can we modify the textof the <h1> element?find itchange it
  24. 24. Selecting by HTML element namehtmlheadbodytitleh1pjQuery Adv...DOM representation of the documentDOCUMENTWhere do...Plan your...1.1 What is jQuery?<!DOCTYPE html><html><head><title>jQuery Adventures</title></head><body><h1>Where do you want to go?</h1><p>Plan your next adventure.</p></body></html>HTML document
  25. 25. Selecting by HTML element name$("h1")htmlheadbodytitleh1h1pjQuery Adv...DOM representation of the documentDOCUMENTWhere do...Plan your...1.1 What is jQuery?;
  26. 26. "Where do you want to go"Fetching an element’s text1.1 What is jQuery?htmlheadbodytitleh1pjQuery Adv...DOM representation of the documentDOCUMENTPlan your...Where do...text() is a method offered by jQuery($("h1").text );
  27. 27. Modifying an element’s texthtmlheadbodytitleh1pjQuery Adv...DOM representation of the documentDOCUMENTWhere to?Plan your...1.1 What is jQuery?text() also allows to modify the text node$("h1").text( );"Where to?"
  28. 28. DOMJavaScript may execute before the DOM loadsHTML1.1 What is jQuery?100%0% 50%$("h1").text( );"Where to?"We need to make sure the DOM has finished loading theHTML content before we can reliably use jQuery.h1 wasn’t in the DOM yet!
  29. 29. DOM“I’m ready!”Listen for “I’m ready” then run <code>The DOM ready eventHTML1.1 What is jQuery?100%0% 50%How can we listen for this signal?
  30. 30. DOM“I’m ready!”Listening for document ready1.1 What is jQuery?jQuery(document).ready(function(){});Will only run this code once the DOM is “ready”<code>
  31. 31. Our completed code1.1 What is jQuery?jQuery(document).ready(function(){});$("h1").text("Where to?");
  32. 32. Using jQuery
  33. 33. Getting started<script src="jquery.min.js"></script><script src="application.js"></script>1.2 Using jQuerydownload jQueryload it in your HTML document12start using it3
  34. 34. find themmodify their textChanging multiple elements at onceHTML documentHow do we change the text ofevery <li> in this page?<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>1.2 Using jQuery
  35. 35. Load HTML into the DOMHTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul> ulRomeliParisliRioli
  36. 36. Selecting multiple elements$("li")HTML documentbodyh1lililih2Where do...Plan your...1.2 Using jQueryulRomeliParisliRioli;<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>
  37. 37. Modifying each of their text nodesHTML documentbodyh1h2Where do...Plan your...1.2 Using jQueryullilili.text("Orlando");$("li")RomeParisRio<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>OrlandoOrlandoOrlando
  38. 38. We can find elements by ID or Classp { ... }#container { ... }.articles { ... }$("p");$("#container");$(".articles");1.2 Using jQueryCSS jQuery
  39. 39. find it using the IDChanging multiple elements at onceHTML documentHow do we specifically select the <ul>that has a “destinations” ID?<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>1.2 Using jQuery
  40. 40. Selecting by unique ID$("#destinations");HTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul> ulRomeliParisliRioliid="destinations"class="promo"ul
  41. 41. find it using the classChanging multiple elements at onceHTML documentHow can we select just the <li> thathas a “promo” class attribute?<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>1.2 Using jQuery
  42. 42. Selecting by Class Name$(".promo");HTML documentbodyh1h2Where do...Plan your...1.2 Using jQuery<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul> ulRomeliParisliRioli class="promo"id="destinations"li
  43. 43. 2level
  44. 44. Searching the DOM
  45. 45. 2.1 Searching the DOMSelecting descendantsHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>How do we find the <li> elements that areinside of the <ul> with a “destinations” ID?descendant selector
  46. 46. lilili<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Paris</li><li>Rome</li><li class=promo>Rio</li></ul>Using the descendant selector$("#destinations li");HTML documentbodyh1h2Where do...Plan your...ulRomeliParisliRiolithe space matters2.1 Searching the DOMparent descendant
  47. 47. <li>Paris</li><li>Rome</li><li class=promo>Rio</li><h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li><ul id="france"></ul></li></ul><h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations">HTML documentHow do we find only the <li> elements that arechildren of the “destinations” <ul>?descendant selector?2.1 Searching the DOMSelecting direct childrenHTML document
  48. 48. ulliliParislililililiSelecting direct children$("#destinations li");HTML documentbodyulRomeRioli2.1 Searching the DOM...we don’t want this<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li><ul id="france"><li>Paris</li></ul></li><li class=promo>Rio</li></ul>
  49. 49. How do we find only the <li> elements that aredirect children of the “destinations” <ul> then?child selectorSelecting only direct childrenHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li><ul id="france"><li>Paris</li></ul></li><li class=promo>Rio</li></div>2.1 Searching the DOM
  50. 50. liliParisullilililibodyulRomeRioli...Selecting only direct children$("#destinations > li");HTML documentthe sign mattersparent childnot selected<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li><ul id="france"><li>Paris</li></ul></li><li class=promo>Rio</li></ul>
  51. 51. How do we find only elementswith either a “promo” class or a “france” IDmultiple selectorSelecting multiple elementsHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li><ul id="france"><li>Paris</li></ul></li><li class=promo>Rio</li></ul>2.1 Searching the DOM
  52. 52. ulliliulSelecting multiple elements$(".promo, #france");HTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li><ul id="france"><li>Paris</li></ul></li><li class=promo>Rio</li></ul>the comma mattersliliParislibodyulRomeRio...
  53. 53. lilililibodyh1h2Where do...Plan your...ulRomeParisliRio$("#destinations li:first");CSS-like pseudo classesfilter$("#destinations li:last");2.1 Searching the DOM
  54. 54. lilibodyh1h2Where do...Plan your...ulRomeParisliRioliCSS-like pseudo classes$("#destinations li:odd");$("#destinations li:even");#0#1#2watch out, the index starts at 02.1 Searching the DOMlili
  55. 55. Traversing
  56. 56. 2.2 TraversingWalking the DOM by traversing itHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>Can we find all the <li> elements thatthe “destinations” list contains withoutusing a descendant selector?filter by traversing
  57. 57. lilililililiFiltering by traversing$("#destinations li");$("#destinations").find("li");It takes a bit more code, but it’s faster.bodyh1h2Where do...Plan your...ulRomeParisRio2.2 Traversingselection traversal
  58. 58. liliFiltering by traversing$("li:first");$("li").first();bodyh1h2Where do...Plan your...ulRomeParisliRioli2.2 Traversing
  59. 59. liliFiltering by traversing$("li:last");$("li").last();bodyh1h2Where do...Plan your...ulRomeliParisliRio2.2 Traversing
  60. 60. HTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>Walking the DOMCan we find the middle list item, knowingthere is no filter to find it unlike :first or :last?traversing2.2 Traversing
  61. 61. lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeParisliRioliWalking the DOM2.2 Traversing
  62. 62. lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisRioli$("li").first().next();Walking the DOMli2.2 Traversing
  63. 63. lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisRioli$("li").first().next();$("li").first().next().prev();Walking the DOMli2.2 Traversing
  64. 64. HTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><li>Paris</li><li class=promo>Rio</li></ul>Walking up the DOMIf we started by selecting a child, can we figureout what element is its direct parent?traversing up2.2 Traversing
  65. 65. lili$("li").first(); bodyh1h2Where do...Plan your...ulRomeParisliRioliWalking up the DOM2.2 Traversing
  66. 66. ul$("li").first(); bodyh1h2Where do...Plan your...ulRomeliParisliRioli$("li").first().parent();Walking up the DOMli2.2 Traversing
  67. 67. Walking down the DOMHTML document<h1>Where do you want to go?</h1><h2>Travel Destinations</h2><p>Plan your next adventure.</p><ul id="destinations"><li>Rome</li><ul id="france"><li>Paris</li></ul><li class=promo>Rio</li></ul>With a parent that has many children who inturn have their own children, how could wefind only the first generation of children?traversing down2.2 Traversing
  68. 68. Walking the DOM up and down$("#destinations").children("li");children(), unlike find(), only selects direct childrenulliliParislilililibodyulRomeRioli...id="destinations"2.2 Traversing
  69. 69. 3level
  70. 70. Working with the DOM
  71. 71. 3.1 Manipulating the DOM
  72. 72. remove a DOM nodeliDOM representation of the documentDOCUMENTHawaiian Vac...h2Get Pricebuttonp$399.99Appending to the DOMclass="vacation"append a new DOM node123.1 Manipulating the DOM
  73. 73. application.jsAppending to the DOMDOCUMENTh2Get Pricebuttonp$399.99livar price = $(<p>From $399.99</p>);var price = "From $399.99";var price = "<p>From $399.99</p>";Creates a node but doesn’t add it to the DOMPrice node (not in the DOM yet)$(document).ready(function() {// create a <p> node with the price});3.1 Manipulating the DOMclass="vacation"Hawaiian Vac...
  74. 74. DOCUMENTh2Get Pricebuttonliapplication.js.append(<element>).after(<element>) .before(<element>).prepend(<element>)Appending to the DOMways to add this price node to the DOMvar price = $(<p>From $399.99</p>);$(document).ready(function() {});Price node (not in the DOM yet)p$399.993.1 Manipulating the DOMclass="vacation"Hawaiian Vac...
  75. 75. DOCUMENTh2Get PricebuttonliBeforeapplication.js$(.vacation).before(price);$(document).ready(function() {var price = $(<p>From $399.99</p>);});3.1 Manipulating the DOMclass="vacation"Hawaiian Vac...p$399.99Puts the price node before .vacation
  76. 76. liDOCUMENTh2Get Pricebuttonp$399.99Afterapplication.js$(#vacation).before(price);Puts the price node after .vacation$(document).ready(function() {var price = $(<p>From $399.99</p>);});$(.vacation).after(price);3.1 Manipulating the DOMclass="vacation"Hawaiian Vac...button
  77. 77. var price = $(<p>From $399.99</p>);$(.vacation).prepend(price);application.jsAdds the node to the top of .vacation$(document).ready(function() {});PrependliDOCUMENTp$399.99h2Get Pricebutton3.1 Manipulating the DOMclass="vacation"Hawaiian Vac...
  78. 78. application.js3.1 Manipulating the DOMPrepend and AppendPuts the price node at the bottom of .vacation$(.vacation).append(price);$(document).ready(function() {var price = $(<p>From $399.99</p>);});liDOCUMENTp$399.99class="vacation"h2Get PricebuttonHawaiian Vac...
  79. 79. application.js$(document).ready(function() {3.1 Manipulating the DOMRemoving from the DOMRemoves the <button> from the DOM$(button).remove();var price = $(<p>From $399.99</p>);$(.vacation).append(price);});liDOCUMENTp$399.99class="vacation"h2Get PricebuttonHawaiian Vac...
  80. 80. 3.1 Manipulating the DOM
  81. 81. DOCUMENTh2Get Pricebuttonli.appendTo(<element>).insertAfter(<element>) .insertBefore(<element>).prependTo(<element>)Appending to the DOMPrice node (not in the DOM yet)p$399.993.1 Manipulating the DOMclass="vacation"Hawaiian Vac...application.js$(document).ready(function() {var price = $(<p>From $399.99</p>);$(.vacation).append(price);$(button).remove();});price.appendTo($(.vacation));Appends in the same place
  82. 82. Acting on Interaction
  83. 83. $(document).ready(<event handler function>);Passing in a functionfunction() {// executing the function runs the code// between the braces}The ready method takes an event handler function as argumentWe create a function with the function keywordAnd we pass this function as an argument to the ready method.3.2 Acting on Interaction$(document).ready(function() {// this function runs when the DOM is ready});
  84. 84. 3.2 Acting on Interaction
  85. 85. application.jsWatching for ClickDOCUMENTHawaiian Vacationh2Get Pricebuttonli class="vacation"Target all buttonsWatch for any clicksRun the code inside of this function3.2 Acting on Interaction$(button).on(click, function() {// runs when any button is clicked});$(document).ready(function() {// runs when the DOM is ready});.on(<event>, <event handler>)jQuery Object Methods
  86. 86. application.jsRemoving from the DOMDOCUMENTHawaiian Vacationh2Get Pricebuttonliruns when the DOM is readyruns when a button is clicked3.2 Acting on Interaction$(document).ready(function() {$(button).on(click, function() {});// run this function on click});class="vacation"
  87. 87. application.jsRemoving from the DOM3.2 Acting on Interactionvar price = $(<p>From $399.99</p>);$(.vacation).append(price);$(button).remove();$(document).ready(function() {$(button).on(click, function() {});});DOCUMENTHawaiian Vacationh2Get Pricebuttonp$399.99li class="vacation"
  88. 88. Now the price will be shown when we click the button
  89. 89. Refactor using Traversing
  90. 90. What if there are multiple vacation packages?
  91. 91. $(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(.vacation).append(price);application.jsThe price will be appended toboth .vacation elements3.3 Refactor Using TraversingWorking, but with ErrorsulDOCUMENTlipclass="vacation"lipclass="vacation"div id="vacations"Every button will be removed$(button).remove();});});buttonbuttonbuttonbutton
  92. 92. $(this).remove();An Introduction to $(this)application.jsulDOCUMENTlibuttonplibuttonpdivIf clicked, the button will be ‘this’this.remove();Not a jQuery object, needs to be converted3.3 Refactor Using Traversing$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(.vacation).append(price);$(button).remove();});});id="vacations"class="vacation"class="vacation"
  93. 93. application.jsAn Introduction to $(this)3.3 Refactor Using TraversingulDOCUMENTlibuttonplibuttonpdivOnly removes whichever button was clicked$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(.vacation).append(price);});});$(this).remove();class="vacation"class="vacation"id="vacations"
  94. 94. The clicked button will now be removed
  95. 95. application.jsAdds the <p> node after the <button>Traversing from $(this)ulDOCUMENTHawaiian Vac...lih2Get Pricebuttonp$399.99class="vacation"3.3 Refactor Using Traversing$(this).after(price);$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).remove();});});$(.vacation).append(price);
  96. 96. application.jsTraversing from $(this)3.3 Refactor Using TraversingAdd the price as a sibling after buttonulDOCUMENTHawaiian Vac...lih2Get Pricebutton$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).remove();});});$(this).after(price);class="vacation"p$399.99
  97. 97. application.jsWhat if the button is moved?ulDOCUMENTHawaiian Vac...lih2Get Pricebuttonp$399.993.3 Refactor Using TraversingdivIf the button is moved, the price will be movedHow do we keep theprice as a child of <li>?$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).remove();});});$(this).after(price);class="vacation"
  98. 98. application.jsUsing .closest(<selector>)3.3 Refactor Using TraversingulDOCUMENTHawaiian Vac...lih2Get Pricebuttondiv$(this).after(price);$(this).parents(.vacation).append(price);$(this).parent().parent().append(price);p$399.99$(this).closest(.vacation).append(price);class="vacation"
  99. 99. application.js$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).remove();});});ulDOCUMENTHawaiian Vac...lih2Get Pricebuttonp$399.99Our Finished HandlerAdds the <p> node at the bottom of .vacation3.3 Refactor Using Traversing$(this).closest(.vacation).append(price);class="vacation"
  100. 100. The prices will be added at the right place
  101. 101. Traversing and Filtering
  102. 102. How do we allow vacations to have different prices?
  103. 103. <li class="vacation onsale"<h3>Hawaiian Vacation</h3><button>Get Price</button><ul class=comments><li>Amazing deal!</li><li>Want to go!</li></ul></li>index.html$(.vacation).first().data(price);All data attributes begin with ‘data-’"399.99"Tackling the HTMLdata-price=399.99>.data(<name>)jQuery Object Methods.data(<name>, <value>)3.4 Traversing & Filtering
  104. 104. var amount = $(this).closest(.vacation).data(price);application.jsReads from the data-price attributeJoins two strings to create the priceRefactoring ‘Get Price’$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $399.99</p>);$(this).closest(.vacation).append(price);$(this).remove();});});var price = $(<p>From $+amount+</p>);3.4 Traversing & Filtering
  105. 105. application.jsRefactoring ‘Get Price’$(document).ready(function() {$(button).on(click, function() {$(this).closest(.vacation).append(price);$(this).remove();});}); Each vacation can have its own pricevar amount = $(this).closest(.vacation).data(price);var price = $(<p>From $+amount+</p>);3.4 Traversing & Filtering
  106. 106. var amount = $(this).closest(.vacation).data(price);$(this).closest(.vacation).append(price);application.jsReusing jQuery Objects$(document).ready(function() {$(button).on(click, function() {var vacation = $(this).closest(.vacation);var amount = vacation.data(price);vacation.append(price);var price = $(<p>From $+amount+</p>);$(this).remove();});});3.4 Traversing & Filtering
  107. 107. vacation.append(price);var amount = vacation.data(price);application.jsReusing jQuery Objectsvar vacation = $(this).closest(.vacation);$(document).ready(function() {$(button).on(click, function() {var price = $(<p>From $+amount+</p>);$(this).remove();});});We’ll only query the DOMonce for this element3.4 Traversing & Filtering
  108. 108. Each vacation can have its dynamic own price now
  109. 109. application.js$(.vacation).on(click, button, function() {});If we add new buttons anywhere, they will trigger this click handler$(.vacation button).on(click, function() {});On With a SelectorOnly target a ‘button’if it’s inside a ‘.vacation’$(document).ready(function() {$(button).on(click, function() {...});});3.4 Traversing & Filtering
  110. 110. We’ll implement our new filters next
  111. 111. <div id=filters>...<button class=onsale-filter>On Sale Now</button><button class=expiring-filter>Expiring</button>...</div>index.htmlWe’ll highlight vacations with these traitsFiltering HTMLWe’ll write 2 event handlers for our buttons3.4 Traversing & Filtering
  112. 112. application.jsFiltering for Vacations On saledivDOCUMENTbutton class="onsale-filter"button class="expiring-filter"// find all vacations that are on-sale// add a class to these vacations});$(#filters).on(click, .onsale-filter,function() { id="filters"3.4 Traversing & Filtering
  113. 113. Filtering for Vacations On saleulDOCUMENTliullililiclass="vacation onsale"class="vacation"class="vacation"class="comments"$(.vacation.onsale)$(.vacation).filter(.onsale)Finds elements with a classof .vacation and .onsaleapplication.js// find all vacations that are on-sale// add a class to these vacations});$(#filters).on(click, .onsale-filter,function() {lili3.4 Traversing & Filtering
  114. 114. Class Manipulationapplication.jsFiltering for Vacations On sale$(.vacation).filter(.onsale).addClass(highlighted);.addClass(<class>) .removeClass(<class>)$(#filters).on(click, .onsale-filter,function() {$(.vacation).filter(.onsale)// add a class to these vacations});ulDOCUMENTliullilililili3.4 Traversing & Filteringclass="vacation onsale"class="vacation"class="vacation"class="comments"
  115. 115. application.jsFiltering for Vacations On saleFinds only the right vacations Adds a class of ‘highlighted’The same can be done for our expiring filter$(#filters).on(click, .onsale-filter, function() {$(.vacation).filter(.onsale).addClass(highlighted);});$(.vacation).filter(.expiring).addClass(highlighted);});$(#filters).on(click, .expiring-filter, function() {3.4 Traversing & Filtering
  116. 116. How do we make sure not all vacations are highlighted?
  117. 117. application.jsUnhighlighting Vacations$(#filters).on(click, .onsale-filter, function() {$(.vacation).filter(.onsale).addClass(highlighted);});$(.highlighted).removeClass(highlighted);Remove the highlightedclass before adding it back3.4 Traversing & Filtering
  118. 118. We clear the highlighted class on click, onlyhighlighting the targeted vacations
  119. 119. 4level
  120. 120. On DOM Load
  121. 121. 4.1 On DOM Load
  122. 122. .ticket {display: none;}index.htmlHide ticket on page loadAdding Ticket Confirmationfind the ticketshow the ticketwatch for clickClicking this button......will show the ticket<li class="confirmation">...<button>FLIGHT DETAILS</button><ul class="ticket">...</ul></li>4.1 On DOM Load
  123. 123. application.js$(.confirmation).on(click, button, function() {});Using slideDown to Show Elementsindex.htmljQuery Object Methods.slideDown().slideUp().slideToggle()$(this).closest(.confirmation).find(.ticket).slideDown();<li class="confirmation">...<ul class="ticket">...</ul></li><button>FLIGHT DETAILS</button>4.1 On DOM LoadSearches up through ancestors Searches down through children
  124. 124. Why doesn’t the button work?
  125. 125. alert(Hello);Alert and Length4.1 On DOM Load$(li).length;3To query how many nodes are on a page.
  126. 126. $(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});application.jsalert($(button).length);The alert dialogDebugging with Alert4.1 On DOM Load
  127. 127. application.js$(document).ready(function() {});The button is found after the DOM has loadedWe Forgot $(document).ready() alreadyalert($(button).length);$(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});4.1 On DOM Load
  128. 128. Now that the DOM has loaded, jQuery can find our button
  129. 129. Expanding on on()
  130. 130. What if we also want to show the ticket when theyhover over the <h3> tag?
  131. 131. application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});});What event should we watch for?Deciding on an Event$(.confirmation).on(?, h3, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});Fires when the mouse is first positioned over the elementclickMouse Eventsdblclickfocusinfocusoutmouseovermouseup mouseout mouseleavemousemove mouseentermousedown4.2 Expanding on on()
  132. 132. application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});$(.confirmation).on( , h3, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});});Mouse EventsShow the ticket when the mouseis positioned over the h3mouseenter4.2 Expanding on on()
  133. 133. We have two ways of showing the ticket now
  134. 134. application.js$(document).ready(function() {$(.confirmation).on(click, button, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});$(.confirmation).on(mouseenter, h3, function() {$(this).closest(.confirmation).find(.ticket).slideDown();});});Extract out and name our event handlerRefactoring Handler FunctionsThis code is duplicated, how can we refactor this?showTicket () {function$(this).closest(.confirmation).find(.ticket).slideDown();}4.2 Expanding on on()
  135. 135. application.js$(document).ready(function() {$(.confirmation).on(click, button, showTicket);$(.confirmation).on(mouseenter, h3, showTicket);});Don’t add () at the end - that would execute the function immediatelyRefactoring Handler FunctionsshowTicket () {function$(this).closest(.confirmation).find(.ticket).slideDown();}4.2 Expanding on on()
  136. 136. Now the exact same code is run for both events
  137. 137. Keyboard Events
  138. 138. Changing this “Tickets” input field should recalculate the total
  139. 139. <div class="vacation" data-price=399.99><h3>Hawaiian Vacation</h3><p>$399.99 per ticket</p><p>Tickets:<input type=number class=quantity value=1 /></p></div><p>Total Price: $<span id=total>399.99</span></p>index.html...we’ll update the calculated price hereWhen this updates...Trip Planner Page4.3 Keyboard Events
  140. 140. Keyboard Events Form Events$(document).ready(function() {$(.vacation).on(?, .quantity, function() {});});application.jshttp://api.jquery.com/category/events/keyboard-events/http://api.jquery.com/category/events/form-events/Which event should we use?keydownkeypresskeyupblur changefocusselectsubmitKeyboard and Form Events4.3 Keyboard Events
  141. 141. $(document).ready(function() {$(.vacation).on(keyup, .quantity, function() {});});application.jsWriting our Event HandlerDOCUMENTli .vacationspanpinput#totalvar price = $(this).closest(.vacation).data(price);Returns price as a stringUse + to convert the string to a number// Get the price for this vacation.quantityp399.99399.99// Get the quantity entered// Set the total to price * quantity4.3 Keyboard Eventsvar price = +$(this).closest(.vacation).data(price);
  142. 142. application.jsGetting the Quantity of TicketsDOCUMENTli .vacationspanpinput .quantityp#totaljQuery Object Methods.val().val(<new value>)Sets quantity to a numbervar quantity = this.val(); Errors - not a jQuery objectvar quantity = $(this).val(); Sets quantity to a stringvar price = +$(this).closest(.vacation).data(price);$(document).ready(function() {$(.vacation).on(keyup, .quantity, function() {});});// Get the quantity entered// Set the total to price * quantityvar quantity = +$(this).val();22
  143. 143. application.jsSetting the Total PriceDOCUMENTli .vacationspanpinput .quantityp#totalYou can pass a number or a string to the .text() method$(#total).text(price * quantity);4.3 Keyboard Events$(document).ready(function() {$(.vacation).on(keyup, .quantity, function() {});});// Set the total to price * quantityvar price = +$(this).closest(.vacation).data(price);var quantity = +$(this).val();
  144. 144. application.jsThe Completed Event HandlerDOCUMENTli .vacationspanpinput .quantityp#totalWhenever the quantity is changed, the total will be updated4.3 Keyboard Events$(document).ready(function() {$(.vacation).on(keyup, .quantity, function() {});});var price = +$(this).closest(.vacation).data(price);var quantity = +$(this).val();$(#total).text(price * quantity);
  145. 145. The total changesimmediately as we wanted
  146. 146. Link Layover
  147. 147. Clicking Show Comments will cause them to fade in
  148. 148. Clicking this link...Preparing for FlightulDOCUMENTShow Commentslialiulli...will show the comments.vacation.expand.comments.comments {display: none;}application.cssapplication.jsWe need to write the event handler// Find the comments ul// Show the comments ul$(document).ready(function() {$(.vacation).on(click, .expand, function() {});});4.4 Link Layover
  149. 149. Preparing for FlightulDOCUMENTShow Commentslialiulli.vacation.expand.commentsFind the .comments ul using traversing$(this).closest(.vacation).find(.comments)application.js// Find the comments ul// Show the comments ul$(document).ready(function() {$(.vacation).on(click, .expand, function() {});});4.4 Link Layover
  150. 150. jQuery Object MethodsPreparing for Flight.fadeToggle().fadeIn() .fadeOut()These are similar to the slide methods$(document).ready(function() {$(.vacation).on(click, .expand, function() {$(this).closest(.vacation).find(.comments)// Show the comments ul});});ulDOCUMENTShow Commentslialiulli.vacation.expand.commentsapplication.js4.4 Link Layover
  151. 151. $(document).ready(function() {$(.vacation).on(click, .expand, function() {$(this).closest(.vacation).find(.comments)});});ulDOCUMENTShow CommentslialiullifadeIn() .comments on first click,fadeOut() .comments on next click.Handling the Click.vacation.expand.comments4.4 Link Layoverapplication.js.fadeToggle();
  152. 152. Why does the page jump to the top?
  153. 153. <a href=# class=expand>Show Comments</a>index.htmlHow the Browser Handles the ClickulDOCUMENTShow Commentslialiulli.vacation.expand.commentsThe click event will “bubble up”to each parent node4.4 Link LayoverFollows the link!(goes to the top of the page)
  154. 154. });The Event ObjectAdd the event parameterapplication.jsDOM TREEulDOCUMENTShow Commentslialiulli.vacation.expand.comments$(document).ready(function() {$(.vacation).on(click, .expand,function(event) {$(this).closest(.vacation).find(.comments).fadeToggle();});4.4 Link Layover
  155. 155. event.stopPropagation()DOM TREEulDOCUMENTShow Commentslialiulli.vacation.expand.commentsThe browser will still handle the click event but will prevent itfrom “bubbling up” to each parent node.$(document).ready(function() {$(.vacation).on(click, .expand,function(event) {event.stopPropagation();$(this).closest(.vacation).find(.comments).fadeToggle();});});4.4 Link Layoverapplication.js
  156. 156. $(document).ready(function() {$(.vacation).on(click, .expand,function(event) {$(this).closest(.vacation).find(.comments).fadeToggle();});});The click event will “bubble up” but the browser won’t handle itevent.preventDefault()DOM TREEulDOCUMENTShow Commentslialiulli.vacation.expand.commentsevent.preventDefault();4.4 Link Layoverapplication.js
  157. 157. We’re preventing the default action of the browser now.
  158. 158. 5level
  159. 159. Taming CSS
  160. 160. HTMLCSSJavaScriptcontentstylebehaviorSeparation of Concerns5.1 Taming CSSTo style something based on userinteraction, which would we use?
  161. 161. 5.1 Taming CSSulDOM representationDOCUMENTli .vacationdiv #vacations...and allow people to clickon the <li> elementChanging our Stylep .priceLet’s make all .vacation elements clickable...
  162. 162. 5.1 Taming CSSapplication.jsChanging the Style$(this).css(background-color, #252b30).css(border-color, 1px solid #967);$(this).css({background-color: #252b30,border-color: 1px solid #967});Passing in a JavaScript Object as an argument is a common jQuery patternulDOM representationDOCUMENTli .vacationdiv #vacationspjQuery Object Methods.css(<attr>, <value>).css(<attr>).css(<object>).price$(this).css(background-color, #252b30);$(this).css(border-color, 1px solid #967);});});$(document).ready(function() {$(#vacations).on(click, .vacation, function() {
  163. 163. 5.1 Taming CSSShowing the PriceulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.jsjQuery Object Methods.show().hide()$(this).find(.price).css(display, block);.price$(this).find(.price).show();Same as CSS syntax, but easier to read and understand});});$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).css({background-color: #252b30,border-color: 1px solid #967});
  164. 164. 5.1 Taming CSSShowing the PriceulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js.priceHighlights the Vacation Package and shows the price});});$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).find(.price).show();$(this).css({background-color: #252b30,border-color: 1px solid #967});
  165. 165. Our .vacation elements are highlighted when we click on them
  166. 166. 5.1 Taming CSSMoving Styles to External CSSulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js});});.priceCan we move these to a CSS stylesheet?application.cssborder-color: 1px solid #967;}.highlighted .price {display: block;}$(this).css({background-color: #563,border-color: 1px solid #967});$(this).find(.price).show();$(document).ready(function() {$(#vacations).on(click, .vacation, function() {#563;.highlighted {background-color:$(this).addClass(highlighted);
  167. 167. 5.1 Taming CSSMoving Styles to External CSSapplication.js});});It’s now much easier to manipulate with external CSS styles$(document).ready(function() {$(#vacations).on(click, .vacation, function() {ulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.cssborder-color: 1px solid #967;}.highlighted .price {display: block;}#563;.highlighted {background-color:$(this).addClass(highlighted);
  168. 168. 5.1 Taming CSSMoving Styles to External CSSulDOM representationDOCUMENTli .vacationdiv #vacationspapplication.js$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).addClass(highlighted);});});.priceWe can only show price, but how would we hide price?$(this).toggleClass(highlighted);jQuery Object Methods.toggleClass().addClass(<class>).removeClass(<class>)Adds the class if $(this) doesn’t have it, removes it if $(this) already has it
  169. 169. Our refactored page still works, and will be much easier to maintain
  170. 170. Challenges5.1 Taming CSS
  171. 171. Animation
  172. 172. What can we do to add a bit more movement to this?
  173. 173. Takes in a JavaScript objectsimilar to the .css() methodAdding MovementjQuery Object Methods.animate(<object>)ulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.js$(this).css({top: -10px});The box will jump up 10 px$(this).animate({top: -10px});5.2 Animation$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});
  174. 174. Adding MovementulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsWill adjust a CSS property pixel by pixel in order to animate it5.2 Animation$(this).animate({top: -10px});$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});
  175. 175. Our animation can slide up but not slide down
  176. 176. Moving Back DownulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsHow do we set ‘top’ to ‘0px’ if a second click occurs?“If statements” allow your code to make decisions at runtime5.2 Animation$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});$(this).animate({top: -10px});} else {// animate the vacation up}// animate the vacation back downif(<vacation has the class highlighted>) {
  177. 177. Moving Back DownulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsjQuery Object Methods.hasClass(<class>)$(this).hasClass(highlighted)Returns true or false5.2 Animationtrue;$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});$(this).animate({top: -10px});$(this).animate({top: 0px});} else {}if(<vacation has the class highlighted>) {
  178. 178. Moving Back Downapplication.jsOur vacation package will move up and down5.2 AnimationulDOM representationDOCUMENTli .vacationdiv #vacationsp .price$(this).hasClass(highlighted)$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});$(this).animate({top: -10px});$(this).animate({top: 0px});} else {}if( ) {
  179. 179. Could we speed this up a little? Our customers don’t have all day.
  180. 180. Changing the Speed$(this).animate({top: -10px});$(this).animate({top: -10px}, 400);We can optionally pass in the speed as asecond argument to animate()$(this).animate({top: -10px}, fast);$(this).animate({top: -10px}, 200);$(this).animate({top: -10px}, slow);$(this).animate({top: -10px}, 600);Effects methods like animate(), slideToggle() and fadeToggle()can also be given a specific speed as a String or in milliseconds5.2 Animation
  181. 181. $(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);if($(this).hasClass(highlighted)) {} else {}});});Moving Back DownulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsAnd with this we now have specific speeds for our animation5.2 Animation$(this).animate({top: -10px}, fast);$(this).animate({top: 0px}, fast);
  182. 182. Our jQuery animation is now using a ‘fast’ speed
  183. 183. The Next Step with CSS AnimationsulDOM representationDOCUMENTli .vacationdiv #vacationsp .priceapplication.jsif($(this).hasClass(highlighted)) {$(this).animate({top: -10px}, fast);} else {$(this).animate({top: 0px}, fast);}5.2 AnimationIsn’t this still styling? Shouldn’t it be inside of a stylesheet?$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});
  184. 184. Animation Durationapplication.js5.2 Animationtransition: top 0.2s;}.highlighted {top: -10px;}Will only work with browsers that implement CSS transitions.vacation {application.css});});$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);ulDOM representationDOCUMENTli .vacationdiv #vacationsp .price
  185. 185. Working with Modern Browsers5.2 Animationapplication.css-moz-transition: top 0.2s;-o-transition: top 0.2s;-webkit-transition: top 0.2s;Unlike jQuery, with CSS we haveto account for specific browsers.vacation {application.js$(document).ready(function() {$(#vacations).on(click, .vacation, function() {$(this).toggleClass(highlighted);});});ulDOM representationDOCUMENTli .vacationdiv #vacationsp .pricetransition: top 0.2s;}.highlighted {top: -10px;}
  186. 186. CSS Animations are a huge topic, but worth looking into

×