Codeschool Try Jquery
Codeschool Try Jquery
level
What is jQuery?
elements in an HTML document HTML content to what a user does and react accordingly content on the page over the network to fetch new content
Changing content
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>
nd it
DOM
1.1 What is jQuery?
browser
0% 50% 100%
DOM
The DOM DOCUMENT html head title jQuery Adven... body h1 Where do... p Plan your...
Inside the DOM, HTML elements become nodes which have relationships with one another.
node types:
element
text
JavaScript
node types:
element
text
Requests a Webpage
Web Browser
DOM
HTML
a r e t In
JavaScript
s t c
th i w
JavaScript
DOM DOM
DOM DOM
If our JavaScript uses jQuery to interact with the DOM then it will work on most modern browsers.
jQuery(<code>);
JavaScript
jQuery(document);
JavaScript
jQuery selectors
jQuery("h1"); jQuery("p");
$("h1"); $("p");
short & sweet syntax
DOM representation of the document DOCUMENT html head title jQuery Adv... body h1 Where do... p Plan your...
$("h1") ;
$("h1").text();
"Where do you want to go"
HTML
0%
50%
100%
DOM
We need to make sure the DOM has finished loading the HTML content before we can reliably use jQuery.
HTML
0%
50%
100%
DOM
Im ready!
DOM
Im ready!
Using jQuery
Getting started
1 2
download jQuery load it in your HTML document
<script src="jquery.min.js"></script>
start using it
<script src="application.js"></script>
How do we change the text of every <li> in this page? nd them modify their text
$("li") ;
li Rio
$("li").text("Orlando");
li Orlando Rio
jQuery
$("p"); $("#container"); $(".articles");
How do we specically select the <ul> that has a destinations ID? nd it using the ID
Selecting by unique ID
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>
$("#destinations");
li
class="promo" Rio
How can we select just the <li> that has a promo class attribute? nd it using the class
$(".promo");
li
class="promo" Rio
level
Selecting descendants
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>
How do we nd the <li> elements that are inside of the <ul> with a destinations ID?
descendant selector
parent
descendant
How do we nd only the <li> elements that are children of the destinations <ul>?
descendant selector?
$("#destinations li");
How do we nd only the <li> elements that are direct children of the destinations <ul> then?
child selector
not selected
parent
child
lter
#0 #1 #2
li Paris
li Rio
Traversing
Can we nd all the <li> elements that the destinations list contains without using a descendant selector?
lter by traversing
2.2 Traversing
Filtering by traversing
$("#destinations li");
body h1 Where do...
$("#destinations").find("li");
selection
traversal
li Rio
2.2 Traversing
Filtering by traversing
$("li:first");
body h1 Where do...
$("li").first();
2.2 Traversing
Filtering by traversing
$("li:last");
body h1 Where do...
$("li").last();
2.2 Traversing
Can we nd the middle list item, knowing there is no lter to nd it unlike :rst or :last?
traversing
2.2 Traversing
2.2 Traversing
$("li").first().next();
2.2 Traversing
$("li").first().next();
$("li").first().next().prev();
2.2 Traversing
If we started by selecting a child, can we gure out what element is its direct parent?
traversing up
2.2 Traversing
2.2 Traversing
$("li").first().parent();
2.2 Traversing
With a parent that has many children who in turn have their own children, how could we nd only the rst generation of children?
traversing down
2.2 Traversing
2.2 Traversing
level
DOM representation of the document DOCUMENT li class="vacation" h2 Hawaiian Vac... button Get Price p $399.99
var price = "From $399.99"; var price = "<p>From $399.99</p>"; var price = $('<p>From $399.99</p>'); Creates a node but doesnt add it to the DOM
$(document).ready(function() { var price = $('<p>From $399.99</p>'); }); ways to add this price node to the DOM
.append(<element>) .after(<element>)
.prepend(<element>)
Price node (not in the DOM yet)
.before(<element>)
p $399.99
Before
application.js
After
application.js
Prepend
application.js
$(document).ready(function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $('button').remove(); }); Removes the <button> from the DOM
$(document).ready(function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $('button').remove(); }); Appends in the same place
.appendTo(<element>) .insertAfter(<element>) .prependTo(<element>) .insertBefore(<element>)
DOCUMENT li class="vacation" h2 Hawaiian Vac... button Get Price Price node (not in the DOM yet) p $399.99
price.appendTo($('.vacation'));
Acting on Interaction
Passing in a function
$(document).ready(<event handler function>); The ready method takes an event handler function as argument function() { // executing the function runs the code // between the braces } We create a function with the function keyword $(document).ready(function() { // this function runs when the DOM is ready }); And we pass this function as an argument to the ready method.
$(document).ready(function() { // runs when the DOM is ready }); Target all buttons
$('button').on('click', function() { // runs when any button is clicked }); Run the code inside of this function
$(document).ready(function() { $('button').on('click', function() { // run this function on click }); }); runs when a button is clicked
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $('button').remove(); }); });
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $('button').remove(); }); }); Every button will be removed The price will be appended to both .vacation elements
An Introduction to $(this)
application.js
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $('button').remove(); }); If clicked, the button will be this }); this.remove();
Not a jQuery object, needs to be converted
$(this).remove();
An Introduction to $(this)
application.js
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $(this).remove(); }); }); Only removes whichever button was clicked
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $('.vacation').append(price); $(this).remove(); }); }); $(this).after(price);
Adds the <p> node after the <button>
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $(this).after(price); $(this).remove(); }); }); Add the price as a sibling after button
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $(this).after(price); $(this).remove(); }); }); If the button is moved, the price will be moved How do we keep the price as a child of <li>?
Using .closest(<selector>)
application.js
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $(this).closest('.vacation').append(price); $(this).remove(); }); });
<li class="vacation onsale" data-price='399.99'> <h3>Hawaiian Vacation</h3> <button>Get Price</button> <ul class='comments'> <li>Amazing deal!</li> <li>Want to go!</li> </ul> All data attributes begin with data- </li>
$('.vacation').first().data('price'); "399.99"
$(document).ready(function() { $('button').on('click', function() { var price = $('<p>From $399.99</p>'); $(this).closest('.vacation').append(price); $(this).remove(); }); });
$(document).ready(function() { $('button').on('click', function() { var amount = $(this).closest('.vacation').data('price'); var price = $('<p>From $'+amount+'</p>'); $(this).closest('.vacation').append(price); $(this).remove(); }); }); Each vacation can have its own price
$(document).ready(function() { $('button').on('click', function() { var amount = $(this).closest('.vacation').data('price'); var price = $('<p>From $'+amount+'</p>'); $(this).closest('.vacation').append(price); $(this).remove(); }); });
$(document).ready(function() { $('button').on('click', function() { var vacation = $(this).closest('.vacation'); var amount = vacation.data('price'); var price = $('<p>From $'+amount+'</p>'); vacation.append(price); $(this).remove(); }); });
On With a Selector
application.js
If we add new buttons anywhere, they will trigger this click handler
$('.vacation button').on('click', function() {}); $('.vacation').on('click', 'button', function() {}); Only target a button if its inside a .vacation
Filtering HTML
index.html
<div id='filters'> ... <button class='onsale-filter'>On Sale Now</button> <button class='expiring-filter'>Expiring</button> ... </div>
Well write 2 event handlers for our buttons Well highlight vacations with these traits
$('#filters').on('click', '.onsale-filter', function() { // find all vacations that are on-sale // add a class to these vacations });
button
button class="expiring-filter"
$('#filters').on('click', '.onsale-filter', function() { // find all vacations that are on-sale // add a class to these vacations });
li li
$('.vacation.onsale')
li li
class="vacation" class="vacation"
$('.vacation').filter('.onsale')
li li
Class Manipulation
.addClass(<class>) .removeClass(<class>)
li li
class="vacation" class="vacation"
$('.vacation').filter('.onsale').addClass('highlighted');
Unhighlighting Vacations
application.js
We clear the highlighted class on click, only highlighting the targeted vacations
level
On DOM Load
<li class="confirmation"> Clicking this button... ... <button>FLIGHT DETAILS</button> <ul class="ticket">...</ul> </li> ...will show the ticket
application.js
$('.confirmation').on('click', 'button', function() { $(this).closest('.confirmation').find('.ticket').slideDown(); }); Searches up through ancestors Searches down through children
$('li').length;
Now that the DOM has loaded, jQuery can nd our button
Expanding on on()
What if we also want to show the ticket when they hover over the <h3> tag?
Deciding on an Event
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(); }); What event should we watch for? });
Mouse Events
click dblclick
Mouse Events
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(); }); Show the ticket when the mouse }); is positioned over the h3
$(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(); }); This code is duplicated, how can we refactor this? });
function showTicket () { $(this).closest('.confirmation').find('.ticket').slideDown(); } $(document).ready(function() { $('.confirmation').on('click', 'button', showTicket); $('.confirmation').on('mouseenter', 'h3', showTicket); });
Dont add () at the end - that would execute the function immediately
Keyboard Events
<div class="vacation" data-price='399.99'> <h3>Hawaiian Vacation</h3> <p>$399.99 per ticket</p> <p> When this updates... Tickets: <input type='number' class='quantity' value='1' /> </p> </div> <p>Total Price: $<span id='total'>399.99</span></p> ...well update the calculated price here
$(document).ready(function() { $('.vacation').on('?', '.quantity', function() { }); Which event should we use? });
Keyboard Events
keypress keydown keyup
Form Events
blur focus select submit change
http://api.jquery.com/category/events/keyboard-events/ http://api.jquery.com/category/events/form-events/
.val()
Link Layover
.expand
Show Comments ul
.comments
li li
.expand
li li
.expand
Show Comments ul
.comments
li li
.expand
Show Comments ul
.comments
li li
.expand
Show Comments ul
.comments
li li
DOM TREE
.expand
Show Comments ul
.comments
li
li
event.stopPropagation()
application.js DOCUMENT ul li
.vacation
DOM TREE
$(document).ready(function() { $('.vacation').on('click', '.expand', function(event) { event.stopPropagation(); $(this).closest('.vacation') .find('.comments') .fadeToggle(); }); });
.expand
Show Comments ul
.comments
li li
The browser will still handle the click event but will prevent it from bubbling up to each parent node.
event.preventDefault()
application.js DOCUMENT ul li
.vacation
DOM TREE
.expand
Show Comments ul
.comments
li li
The click event will bubble up but the browser wont handle it
level
Taming CSS
Separation of Concerns
JavaScript
behavior
ul li
.vacation
p .price
ul li
.vacation
p .price $(this).css('background-color', '#252b30') .css('border-color', '1px solid #967'); $(this).css({'background-color': '#252b30', 'border-color': '1px solid #967'});
ul li
.vacation
p .price
ul li
.vacation
p .price
ul li
.vacation
p .price
.highlighted { background-color: #563; border-color: 1px solid #967; } .highlighted .price { display: block; }
ul li
.vacation
p .price
ul li
.vacation
We can only show price, but how would we hide price? $(this).toggleClass('highlighted'); Adds the class if $(this) doesnt have it, removes it if $(this) already has it
p .price
Our refactored page still works, and will be much easier to maintain
Challenges
5.1 Taming CSS
Animation
Adding Movement
application.js $(document).ready(function() { $('#vacations').on('click', '.vacation', function() { $(this).toggleClass('highlighted'); }); });
ul li
.vacation
$(this).css({'top': '-10px'});
p .price
5.2 Animation
Adding Movement
application.js $(document).ready(function() { $('#vacations').on('click', '.vacation', function() { $(this).toggleClass('highlighted'); $(this).animate({'top': '-10px'}); }); });
ul li
.vacation
p .price
5.2 Animation
ul li
.vacation
p .price
5.2 Animation
ul li
.vacation
p .price
5.2 Animation
ul li
.vacation
p .price
5.2 Animation
Could we speed this up a little? Our customers dont have all day.
Effects methods like animate(), slideToggle() and fadeToggle() can also be given a specic speed as a String or in milliseconds
5.2 Animation
ul li
.vacation
p .price
And with this we now have specic speeds for our animation
5.2 Animation
ul li
.vacation
p .price
5.2 Animation
Animation Duration
application.js $(document).ready(function() { $('#vacations').on('click', '.vacation', function() { $(this).toggleClass('highlighted'); }); }); application.css .vacation { transition: top 0.2s; } .highlighted { top: -10px; }
ul li
.vacation
p .price
5.2 Animation
ul li
.vacation
p .price
5.2 Animation