[go: up one dir, main page]

0% found this document useful (0 votes)
61 views187 pages

Codeschool Try Jquery

The document discusses how jQuery can be used to modify HTML elements on a page. It explains how the browser loads HTML into the DOM, and how jQuery uses CSS selectors to find elements. It then demonstrates how jQuery can be used to select an element by its name, fetch its text content, and modify that text.

Uploaded by

chyon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views187 pages

Codeschool Try Jquery

The document discusses how jQuery can be used to modify HTML elements on a page. It explains how the browser loads HTML into the DOM, and how jQuery uses CSS selectors to find elements. It then demonstrates how jQuery can be used to select an element by its name, fetch its text content, and modify that text.

Uploaded by

chyon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

How does this work?

flight time 3:00

video lessons

challenges

points & badges


points & badges
In order to learn jQuery you need to know:

☑ HTML
content

☑ CSS
style

JavaScript
behavior
1
level
What is jQuery?
What you can do with jQuery

reveal interface elements


1.1 What is jQuery?
What you can do with jQuery

change content based on user actions


1.1 What is jQuery?
What you can do with jQuery

toggle CSS classes to highlight an element


1.1 What is jQuery?
jQuery makes it easy to:

find elements in an HTML document

change HTML content

listen to what a user does and react accordingly

animate content on the page

talk over the network to fetch new content

1.1 What is jQuery?


Changing content
HTML document

<!DOCTYPE html> How can we modify the text


<html> of the <h1> element?
<head>
<title>jQuery Adventures</title>
</head> find it
<body>
<h1>Where do you want to go?</h1>
<p>Plan your next adventure.</p>
change it
</body>
</html>

1.1 What is jQuery?


Finding the proper HTML
HTML document

<!DOCTYPE html> find it


<html>
<head>
<title>jQuery Adventures</title>
How can we search
</head> through our html?
<body>
<h1>Where do you want to go?</h1>
<p>Plan your next adventure.</p>
</body>
</html>

We need to understand how our browser


organizes the HTML it receives.

1.1 What is jQuery?


Document Object Model
A tree-like structure created by browsers so we can
quickly find HTML Elements using JavaScript.

“DOM”

1.1 What is jQuery?


Loading HTML into the DOM
HTML document

<!DOCTYPE html>
<html>
<head>
<title>jQuery Adventures</title>
browser
</head>
<body>
<h1>Where do you want to go?</h1> 0% 50% 100%
DOM
<p>Plan your next adventure.</p>
</body>
</html>

1.1 What is jQuery?


What does that DOM structure look like?
The DOM
HTML document
DOCUMENT
<!DOCTYPE html>
<html>
html
<head>
<title>jQuery Adventures</title> head
</head>
<body> title
<h1>Where do you want to go?</h1> jQuery Adven...
<p>Plan your next adventure.</p>
</body> body
</html> h1
Where do...
Inside the DOM, HTML elements become “nodes” p
which have relationships with one another.
Plan your...

node types: element text

1.1 What is jQuery?


How do we search through the DOM?
The DOM

DOCUMENT

html
head
title
JavaScript
jQuery Adven...
body JavaScript gives developers a
h1 language to interact with the DOM.
Where do...
p
Plan your...

node types: element text

1.1 What is jQuery?


How do we find things using the DOM?

Web Server Web Browser


Requests a Webpage
Loads into
DOM
Sends the HTML
HTML HTML
+ other files needed ith
s w
c t
to load that page e r a
In t

JavaScript JavaScript

1.1 What is jQuery?


Of course, there’s a catch
DOM each browser has a slightly
different DOM interface

DOM

DOM

JavaScript DOM

DOM

1.1 What is jQuery?


jQuery to the rescue!
DOM

DOM

DOM

JavaScript DOM
If our JavaScript uses jQuery to interact
with the DOM then it will work on most DOM
modern browsers.
1.1 What is jQuery?
Basic jQuery usage
this is the jQuery function

jQuery(<code>);

JavaScript

1.1 What is jQuery?


How jQuery Accesses The DOM
The DOM

jQuery(document);

JavaScript

But how can we search through the DOM?

1.1 What is jQuery?


We need to use CSS selectors
HTML document

<!DOCTYPE html> CSS selectors


<html>
<head> h1 { font-size: 3em; }
<title>jQuery Adventures</title>
</head>
<body> p { color: blue; }
<h1>Where do you want to go?</h1>
<p>Plan your next adventure.</p>
</body>
</html>

1.1 What is jQuery?


Using the jQuery function to find nodes
HTML document jQuery selectors

<!DOCTYPE html>
<html>
<head>
<title>jQuery Adventures</title>
</head>
<body>
jQuery("h1");

jQuery("p");
= $("h1");

$("p");
short & sweet
<h1>Where do you want to go?</h1> syntax
<p>Plan your next adventure.</p>
</body>
</html>

1.1 What is jQuery?


Changing the content of an element
HTML document

<!DOCTYPE html> How can we modify the text


<html> of the <h1> element?
<head>
<title>jQuery Adventures</title>
</head> find it
<body>
<h1>Where do you want to go?</h1>
<p>Plan your next adventure.</p>
change it
</body>
</html>

1.1 What is jQuery?


Selecting by HTML element name DOM representation of the document
HTML document
DOCUMENT
<!DOCTYPE html>
<html>
html
<head>
<title>jQuery Adventures</title> head
</head>
<body> title
<h1>Where do you want to go?</h1> jQuery Adv...
<p>Plan your next adventure.</p>
</body> body
</html> h1
Where do...
p
Plan your...

1.1 What is jQuery?


Selecting by HTML element name DOM representation of the document

DOCUMENT

html

$("h1") ; head
title
jQuery Adv...
body
h1
Where do...
p
Plan your...

1.1 What is jQuery?


Fetching an element’s text DOM representation of the document

text() is a method offered by jQuery


DOCUMENT

html

$("h1").text(); head
title
"Where do you want to go"
jQuery Adv...
body
h1
Where do...
p
Plan your...

1.1 What is jQuery?


Modifying an element’s text DOM representation of the document

text() also allows to modify the text node


DOCUMENT

html

$("h1").text( "Where to?"); head


title
jQuery Adv...
body
h1
Where to?
p
Plan your...

1.1 What is jQuery?


JavaScript may execute before the DOM loads

HTML 0% 50% 100%


DOM
h1 wasn’t in the DOM yet!

$("h1").text( "Where to?");

We need to make sure the DOM has finished loading the


HTML content before we can reliably use jQuery.

1.1 What is jQuery?


The DOM ready event

HTML 0% 50% 100%


DOM

“I’m ready!”

How can we listen for this signal?

Listen for “I’m ready” then run <code>

1.1 What is jQuery?


Listening for document ready

jQuery(document).ready(function(){
DOM
<code>
});
“I’m ready!”
Will only run this code once the DOM is “ready”

1.1 What is jQuery?


Our completed code

jQuery(document).ready(function(){
$("h1").text("Where to?");
});

1.1 What is jQuery?


Using jQuery
Getting started

1 download jQuery

2 load it in your HTML document

<script src="jquery.min.js"></script>

3 start using it

<script src="application.js"></script>

1.2 Using jQuery


Changing multiple elements at once
HTML document

<h1>Where do you want to go?</h1>


How do we change the text of
<h2>Travel Destinations</h2> every <li> in this page?
<p>Plan your next adventure.</p>
<ul id="destinations"> find them
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li> modify their text
</ul>

1.2 Using jQuery


Load HTML into the DOM
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> h1
<p>Plan your next adventure.</p>
Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li>
Plan your...
<li class='promo'>Rio</li>
</ul> ul
li
Rome
li
Paris
li
Rio

1.2 Using jQuery


Selecting multiple elements
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> h1
<p>Plan your next adventure.</p>
Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li>
Plan your...
<li class='promo'>Rio</li>
</ul> ul
li
Rome
li
Paris
$("li") ; li
Rio

1.2 Using jQuery


Modifying each of their text nodes
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> h1
<p>Plan your next adventure.</p>
Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li>
Plan your...
<li class='promo'>Rio</li>
</ul> ul
li
Rome
Orlando
li
Paris
Orlando
$("li").text("Orlando"); li
Orlando
Rio

1.2 Using jQuery


We can find elements by ID or Class
CSS jQuery
p { ... } $("p");

#container { ... } $("#container");

.articles { ... } $(".articles");

1.2 Using jQuery


Changing multiple elements at once
HTML document

<h1>Where do you want to go?</h1>


How do we specifically select the <ul>
<h2>Travel Destinations</h2> that has a “destinations” ID?
<p>Plan your next adventure.</p>
<ul id="destinations"> find it using the ID
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>

1.2 Using jQuery


Selecting by unique ID
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> h1
<p>Plan your next adventure.</p>
Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li>
Plan your...
<li class='promo'>Rio</li>
</ul> ul id="destinations"
li
Rome
li
Paris
$("#destinations"); li class="promo"
Rio

1.2 Using jQuery


Changing multiple elements at once
HTML document

<h1>Where do you want to go?</h1>


How can we select just the <li> that
<h2>Travel Destinations</h2> has a “promo” class attribute?
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
find it using the class
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>

1.2 Using jQuery


Selecting by Class Name
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> h1
<p>Plan your next adventure.</p>
Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li>
Plan your...
<li class='promo'>Rio</li>
</ul> ul id="destinations"
li
Rome
li
Paris
$(".promo"); li class="promo"
Rio

1.2 Using jQuery


level 2
Searching the DOM
Selecting descendants
HTML document

<h1>Where do you want to go?</h1>


How do we find the <li> elements that are
<h2>Travel Destinations</h2> inside of the <ul> with a “destinations” ID?
<p>Plan your next adventure.</p>
<ul id="destinations"> descendant selector
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>

2.1 Searching the DOM


Using the descendant selector
HTML document
body
<h1>Where do you want to go?</h1>
h1
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p> Where do...
<ul id="destinations">
<li>Rome</li> h2
<li>Paris</li> Plan your...
<li class='promo'>Rio</li>
</ul> ul
li
Rome
the space matters
li
Paris
$("#destinations li");
li
parent descendant Rio

2.1 Searching the DOM


Selecting direct children
HTML document

<h1>Where do you want to go?</h1>


How do we find only the <li> elements that are
<h2>Travel Destinations</h2> children of the “destinations” <ul>?
<p>Plan your next adventure.</p>
<ul id="destinations"> descendant selector?
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</ul>

2.1 Searching the DOM


Selecting direct children
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> ...
<p>Plan your next adventure.</p> ul
<ul id="destinations">
<li>Rome</li> li
<li> Rome
<ul id="france">
<li>Paris</li> li we don’t want this
</ul>
ul
</li>
<li class='promo'>Rio</li> li
</ul>
li Paris
Rio
$("#destinations li");

2.1 Searching the DOM


Selecting only direct children
HTML document

<h1>Where do you want to go?</h1>


How do we find only the <li> elements that are
<h2>Travel Destinations</h2> direct children of the “destinations” <ul> then?
<p>Plan your next adventure.</p>
<ul id="destinations"> child selector
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</div>

2.1 Searching the DOM


Selecting only direct children
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> ...
<p>Plan your next adventure.</p> ul
<ul id="destinations">
<li>Rome</li> li
<li> Rome
<ul id="france">
<li>Paris</li> li
</ul> not selected
ul
</li>
<li class='promo'>Rio</li> li
</ul>
li Paris
the sign matters Rio

$("#destinations > li");

parent child
Selecting multiple elements
HTML document

<h1>Where do you want to go?</h1>


How do we find only elements
<h2>Travel Destinations</h2> with either a “promo” class or a “france” ID
<p>Plan your next adventure.</p>
<ul id="destinations"> multiple selector
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</ul>

2.1 Searching the DOM


Selecting multiple elements
HTML document
body
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2> ...
<p>Plan your next adventure.</p> ul
<ul id="destinations">
<li>Rome</li> li
<li> Rome
<ul id="france">
<li>Paris</li> li
</ul>
ul
</li>
<li class='promo'>Rio</li> li
</ul>
li Paris
Rio
the comma matters

$(".promo, #france");
CSS-like pseudo classes
$("#destinations li:first"); body
h1
$("#destinations li:last"); Where do...
h2
filter
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.1 Searching the DOM


CSS-like pseudo classes
$("#destinations li:odd"); body
h1
$("#destinations li:even"); Where do...
h2
Plan your...
ul
#0 li
Rome
#1 li
Paris
#2 li
watch out, the index starts at 0 Rio

2.1 Searching the DOM


Traversing
Walking the DOM by traversing it
HTML document

<h1>Where do you want to go?</h1>


Can we find all the <li> elements that
<h2>Travel Destinations</h2> the “destinations” list contains without
<p>Plan your next adventure.</p> using a descendant selector?
<ul id="destinations">
<li>Rome</li>
<li>Paris</li>
filter by traversing
<li class='promo'>Rio</li>
</ul>

2.2 Traversing
Filtering by traversing
$("#destinations li"); body
h1
Where do...
$("#destinations").find("li"); h2
Plan your...
ul
li
selection traversal
Rome
li
Paris
It takes a bit more code, but it’s faster. li
Rio

2.2 Traversing
Filtering by traversing
$("li:first"); body
h1
Where do...
$("li").first(); h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Filtering by traversing
$("li:last"); body
h1
Where do...
$("li").last(); h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking the DOM
HTML document

<h1>Where do you want to go?</h1>


Can we find the middle list item, knowing
<h2>Travel Destinations</h2> there is no filter to find it unlike :first or :last?
<p>Plan your next adventure.</p>
<ul id="destinations"> traversing
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>

2.2 Traversing
Walking the DOM
$("li").first(); body
h1
Where do...
h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking the DOM
$("li").first(); body
h1
Where do...
$("li").first().next();
h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking the DOM
$("li").first(); body
h1
Where do...
$("li").first().next();
h2
Plan your...
$("li").first().next().prev(); ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking up the DOM
HTML document

<h1>Where do you want to go?</h1>


If we started by selecting a child, can we figure
<h2>Travel Destinations</h2> out what element is its direct parent?
<p>Plan your next adventure.</p>
<ul id="destinations"> traversing up
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>

2.2 Traversing
Walking up the DOM
$("li").first(); body
h1
Where do...
h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking up the DOM
$("li").first(); body
h1
Where do...
$("li").first().parent();
h2
Plan your...
ul
li
Rome
li
Paris
li
Rio

2.2 Traversing
Walking down the DOM
HTML document

<h1>Where do you want to go?</h1>


With a parent that has many children who in
<h2>Travel Destinations</h2> turn have their own children, how could we
<p>Plan your next adventure.</p> find only the first generation of children?
<ul id="destinations">
<li>Rome</li>
<ul id="france">
traversing down
<li>Paris</li>
</ul>
<li class='promo'>Rio</li>
</ul>

2.2 Traversing
Walking the DOM up and down
$("#destinations").children("li"); body
...
children(), unlike find(), only selects direct children ul id="destinations"
li
Rome

li

ul
li
li Paris
Rio

2.2 Traversing
level 3
Working with the DOM
3.1 Manipulating the DOM
Appending to the DOM DOM representation of the document

1 append a new DOM node DOCUMENT

li class="vacation"
2 remove a DOM node
h2

Hawaiian Vac...
button

Get Price

$399.99

3.1 Manipulating the DOM


Appending to the DOM
application.js
DOCUMENT
$(document).ready(function() {
// create a <p> node with the price li class="vacation"
}); h2

Hawaiian Vac...
button

var price = "From $399.99"; Get Price

Price node (not in the DOM yet)


var price = "<p>From $399.99</p>";
p
var price = $('<p>From $399.99</p>'); $399.99

Creates a node but doesn’t add it to the DOM

3.1 Manipulating the DOM


Appending to the DOM
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
}); h2

ways to add this price node to the DOM Hawaiian Vac...


button

Get Price
.append(<element>) .prepend(<element>)
Price node (not in the DOM yet)

.after(<element>) .before(<element>) p

$399.99

3.1 Manipulating the DOM


Before
application.js
DOCUMENT
$(document).ready(function() {
p
var price = $('<p>From $399.99</p>');
$('.vacation').before(price); $399.99
}); li class="vacation"

Puts the price node before .vacation h2

Hawaiian Vac...
button

Get Price

3.1 Manipulating the DOM


After
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
$('#vacation').before(price);
$('.vacation').after(price); h2
});
Hawaiian Vac...
Puts the price node after .vacation button

Get Price
p

$399.99

3.1 Manipulating the DOM


Prepend
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
$('.vacation').prepend(price); p
});
$399.99
Adds the node to the top of .vacation h2

Hawaiian Vac...
button

Get Price

3.1 Manipulating the DOM


Prepend and Append
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
$('.vacation').append(price); h2
});
Hawaiian Vac...
Puts the price node at the bottom of .vacation button

Get Price
p

$399.99

3.1 Manipulating the DOM


Removing from the DOM
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
$('.vacation').append(price); h2
$('button').remove();
Hawaiian Vac...
});
button
Removes the <button> from the DOM
Get Price
p

$399.99

3.1 Manipulating the DOM


3.1 Manipulating the DOM
Appending to the DOM
application.js
DOCUMENT
$(document).ready(function() {
var price = $('<p>From $399.99</p>'); li class="vacation"
$('.vacation').append(price); h2
$('button').remove();
Hawaiian Vac...
}); Appends in the same place
button

Get Price
.appendTo(<element>) .prependTo(<element>)
Price node (not in the DOM yet)
.insertAfter(<element>) .insertBefore(<element>)
p

$399.99
price.appendTo($('.vacation'));

3.1 Manipulating the DOM


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.


3.2 Acting on Interaction
3.2 Acting on Interaction
Watching for Click
application.js
DOCUMENT
$(document).ready(function() {
li class="vacation"
// runs when the DOM is ready
}); h2

Hawaiian Vacation
Target all buttons button
Watch for any clicks
Get Price
$('button').on('click', function() {
// runs when any button is clicked jQuery Object Methods
}); .on(<event>, <event handler>)

Run the code inside of this function

3.2 Acting on Interaction


Removing from the DOM
application.js runs when the DOM is ready
DOCUMENT
$(document).ready(function() {
li class="vacation"
$('button').on('click', function() {
// run this function on click h2
}); Hawaiian Vacation
}); button

runs when a button is clicked Get Price

3.2 Acting on Interaction


Removing from the DOM
application.js
DOCUMENT
$(document).ready(function() {
li class="vacation"
$('button').on('click', function() {
var price = $('<p>From $399.99</p>'); h2
$('.vacation').append(price); Hawaiian Vacation
$('button').remove(); button
});
Get Price
});
p

$399.99

3.2 Acting on Interaction


Now the price will be shown when we click the button
Refactor using Traversing
What if there are multiple vacation packages?
Working, but with Errors
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { div id="vacations"

var price = $('<p>From $399.99</p>'); ul


$('.vacation').append(price);
li class="vacation"
$('button').remove();
}); button
}); p

li class="vacation"
Every button will be removed
button

p
The price will be appended to
both .vacation elements

3.3 Refactor Using Traversing


An Introduction to $(this)
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { div id="vacations"

var price = $('<p>From $399.99</p>'); ul


$('.vacation').append(price);
li class="vacation"
$('button').remove();
}); button
}); If clicked, the button will be ‘this’ p

li class="vacation"
this.remove();
button
Not a jQuery object, needs to be converted
p

$(this).remove();

3.3 Refactor Using Traversing


An Introduction to $(this)
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { div id="vacations"

var price = $('<p>From $399.99</p>'); ul


$('.vacation').append(price);
li class="vacation"
$(this).remove();
}); button
}); p

Only removes whichever button was clicked li class="vacation"

button

3.3 Refactor Using Traversing


The clicked button will now be removed
Traversing from $(this)
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { ul
var price = $('<p>From $399.99</p>'); li class="vacation"
$('.vacation').append(price); h2
$(this).remove();
Hawaiian Vac...
});
}); button

Get Price

p
$(this).after(price);
$399.99
Adds the <p> node after the <button>

3.3 Refactor Using Traversing


Traversing from $(this)
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { ul
var price = $('<p>From $399.99</p>'); li class="vacation"
$(this).after(price); h2
$(this).remove();
Hawaiian Vac...
});
}); button

Get Price
Add the price as a sibling after button
p

$399.99

3.3 Refactor Using Traversing


What if the button is moved?
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { ul
var price = $('<p>From $399.99</p>'); li class="vacation"
$(this).after(price); h2
$(this).remove();
Hawaiian Vac...
});
}); div

button
If the button is moved, the price will be moved
Get Price
How do we keep the
p
price as a child of <li>?
$399.99

3.3 Refactor Using Traversing


Using .closest(<selector>)
application.js
DOCUMENT
$(this).after(price);
ul

$(this).parent().parent().append(price); li class="vacation"

h2

$(this).parents('.vacation').append(price); Hawaiian Vac...


div

$(this).closest('.vacation').append(price); button

Get Price

$399.99

3.3 Refactor Using Traversing


Our Finished Handler
application.js
DOCUMENT
$(document).ready(function() {
$('button').on('click', function() { ul
var price = $('<p>From $399.99</p>');
li class="vacation"
$(this).closest('.vacation').append(price);
$(this).remove(); h2
});
Hawaiian Vac...
});
button
Adds the <p> node at the bottom of .vacation
Get Price

$399.99

3.3 Refactor Using Traversing


The prices will be added at the right place
Traversing and Filtering
How do we allow vacations to have different prices?
Tackling the HTML
index.html

<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>
</li> All data attributes begin with ‘data-’

jQuery Object Methods


$('.vacation').first().data('price');
"399.99" .data(<name>)

.data(<name>, <value>)

3.4 Traversing & Filtering


Refactoring ‘Get Price’
application.js

$(document).ready(function() {
$('button').on('click', function() {
var price = $('<p>From $399.99</p>');
$(this).closest('.vacation').append(price);
$(this).remove();
});
});
Reads from the data-price attribute

var amount = $(this).closest('.vacation').data('price');


var price = $('<p>From $'+amount+'</p>');

Joins two strings to create the price

3.4 Traversing & Filtering


Refactoring ‘Get Price’
application.js

$(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

3.4 Traversing & Filtering


Reusing jQuery Objects
application.js

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

var vacation = $(this).closest('.vacation');


var amount = vacation.data('price');
vacation.append(price);

3.4 Traversing & Filtering


Reusing jQuery Objects
application.js

$(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();
}); We’ll only query the DOM
});
once for this element

3.4 Traversing & Filtering


Each vacation can have its dynamic own price now
On With a Selector
application.js

$(document).ready(function() {
$('button').on('click', function() {
...
});
});
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 it’s inside a ‘.vacation’

3.4 Traversing & Filtering


We’ll implement our new filters next
Filtering HTML
index.html

<div id='filters'>
...
<button class='onsale-filter'>On Sale Now</button>
<button class='expiring-filter'>Expiring</button>
...
</div>

We’ll write 2 event handlers for our buttons


We’ll highlight vacations with these traits

3.4 Traversing & Filtering


Filtering for Vacations On sale
application.js
DOCUMENT
$('#filters').on('click', '.onsale-filter',
div id="filters"
function() {
// find all vacations that are on-sale button class="onsale-filter"

// add a class to these vacations


button class="expiring-filter"
});

3.4 Traversing & Filtering


Filtering for Vacations On sale
application.js
DOCUMENT
$('#filters').on('click', '.onsale-filter',
ul
function() {
// find all vacations that are on-sale li class="vacation onsale"
// add a class to these vacations
ul class="comments"
});
li

li
$('.vacation.onsale') li class="vacation"

li class="vacation"

$('.vacation').filter('.onsale')

Finds elements with a class


of .vacation and .onsale
3.4 Traversing & Filtering
Filtering for Vacations On sale
application.js
DOCUMENT
$('#filters').on('click', '.onsale-filter',
ul
function() {
$('.vacation').filter('.onsale') li class="vacation onsale"
// add a class to these vacations
ul class="comments"
});
li

Class Manipulation li

li class="vacation"
.addClass(<class>) .removeClass(<class>)
li class="vacation"

$('.vacation').filter('.onsale').addClass('highlighted');

3.4 Traversing & Filtering


Filtering for Vacations On sale
application.js

$('#filters').on('click', '.onsale-filter', function() {


$('.vacation').filter('.onsale').addClass('highlighted');
});

Finds only the right vacations Adds a class of ‘highlighted’

The same can be done for our expiring filter


$('#filters').on('click', '.expiring-filter', function() {
$('.vacation').filter('.expiring').addClass('highlighted');
});

3.4 Traversing & Filtering


How do we make sure not all vacations are highlighted?
Unhighlighting Vacations
application.js

$('#filters').on('click', '.onsale-filter', function() {


$('.highlighted').removeClass('highlighted');
$('.vacation').filter('.onsale').addClass('highlighted');
});

Remove the highlighted


class before adding it back

3.4 Traversing & Filtering


We clear the highlighted class on click, only
highlighting the targeted vacations
level 4
On DOM Load
4.1 On DOM Load
Adding Ticket Confirmation
index.html

<li class="confirmation">
... Clicking this button...
<button>FLIGHT DETAILS</button>
<ul class="ticket">...</ul>
</li>
...will show the ticket

watch for click


.ticket {
display: none;
} find the ticket
Hide ticket on page load
show the ticket

4.1 On DOM Load


Using slideDown to Show Elements
index.html
jQuery Object Methods

<li class="confirmation"> .slideDown()


...
<button>FLIGHT DETAILS</button> .slideUp()
<ul class="ticket">...</ul>
</li>
.slideToggle()

application.js

$('.confirmation').on('click', 'button', function() {


$(this).closest('.confirmation').find('.ticket').slideDown();
});

Searches up through ancestors Searches down through children

4.1 On DOM Load


Why doesn’t the button work?
Alert and Length

alert('Hello');

$('li').length; To query how many nodes are on a page.


3

4.1 On DOM Load


Debugging with Alert
application.js

alert($('button').length);
$('.confirmation').on('click', 'button', function() {
$(this).closest('.confirmation').find('.ticket').slideDown();
});

The alert dialog

4.1 On DOM Load


We Forgot $(document).ready() already
application.js

$(document).ready(function() {
alert($('button').length);
$('.confirmation').on('click', 'button', function() {
$(this).closest('.confirmation').find('.ticket').slideDown();
});
});

The button is found after the DOM has loaded

4.1 On DOM Load


Now that the DOM has loaded, jQuery can find 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 Fires when the mouse is first positioned over the element

click focusin mousedown mousemove mouseover mouseenter

dblclick focusout mouseup mouseout mouseleave

4.2 Expanding on on()


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

4.2 Expanding on on()


We have two ways of showing the ticket now
Refactoring Handler Functions
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();
});
}); This code is duplicated, how can we refactor this?

Extract out and name our event handler

function showTicket () {
$(this).closest('.confirmation').find('.ticket').slideDown();
}

4.2 Expanding on on()


Refactoring Handler Functions
application.js

function showTicket () {
$(this).closest('.confirmation').find('.ticket').slideDown();
}
$(document).ready(function() {
$('.confirmation').on('click', 'button', showTicket);
$('.confirmation').on('mouseenter', 'h3', showTicket);
});

Don’t add () at the end - that would execute the function immediately

4.2 Expanding on on()


Now the exact same code is run for both events
Keyboard Events
Changing this “Tickets” input field should recalculate the total
Trip Planner Page
index.html

<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>

...we’ll update the calculated price here

4.3 Keyboard Events


Keyboard and Form Events
application.js

$(document).ready(function() {
$('.vacation').on('?', '.quantity', function() {
});
}); Which event should we use?

Keyboard Events Form Events


keypress blur select change

keydown focus submit

keyup http://api.jquery.com/category/events/keyboard-events/
http://api.jquery.com/category/events/form-events/

4.3 Keyboard Events


Writing our Event Handler
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('keyup', '.quantity', function() { li .vacation
// Get the price for this vacation
// Get the quantity entered p
// Set the total to price * quantity
input .quantity
});
}); p
span #total
var price = $(this).closest('.vacation').data('price');
'399.99'
Returns price as a string
var price = +$(this).closest('.vacation').data('price');
399.99
Use + to convert the string to a number

4.3 Keyboard Events


Getting the Quantity of Tickets
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('keyup', '.quantity', function() { li .vacation
var price = +$(this).closest('.vacation').data('price');
// Get the quantity entered p
// Set the total to price * quantity
input .quantity
});
}); p
span #total
var quantity = this.val(); Errors - not a jQuery object

var quantity = $(this).val(); Sets quantity to a string jQuery Object Methods


'2' .val(<new value>)

var quantity = +$(this).val(); Sets quantity to a number


.val()
2
Setting the Total Price
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('keyup', '.quantity', function() { li .vacation
var price = +$(this).closest('.vacation').data('price');
var quantity = +$(this).val(); p
// Set the total to price * quantity
input .quantity
});
}); p
span #total
$('#total').text(price * quantity);
You can pass a number or a string to the .text() method

4.3 Keyboard Events


The Completed Event Handler
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('keyup', '.quantity', function() { li .vacation
var price = +$(this).closest('.vacation').data('price');
var quantity = +$(this).val(); p
$('#total').text(price * quantity); input .quantity
});
}); p

Whenever the quantity is changed, the total will be updated span #total

4.3 Keyboard Events


The total changes
immediately as we wanted
Link Layover
Clicking Show Comments will cause them to fade in
Preparing for Flight
application.css
DOCUMENT
.comments {
display: none;
} ul Clicking this link...
li .vacation

a .expand
application.js
Show Comments
$(document).ready(function() {
$('.vacation').on('click', '.expand', function() { ul .comments
// Find the comments ul li
// Show the comments ul
}); li
});

We need to write the event handler ...will show the comments

4.4 Link Layover


Preparing for Flight
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('click', '.expand', function() {
ul
// Find the comments ul
// Show the comments ul li .vacation
});
a .expand
});
Show Comments

$(this).closest('.vacation').find('.comments') ul .comments

Find the .comments ul using traversing li

li

4.4 Link Layover


Preparing for Flight
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('click', '.expand', function() {
ul
$(this).closest('.vacation')
.find('.comments') li .vacation
// Show the comments ul
a .expand
});
}); Show Comments

ul .comments
jQuery Object Methods
li
.fadeIn() .fadeOut() .fadeToggle() li

These are similar to the slide methods

4.4 Link Layover


Handling the Click
application.js
DOCUMENT
$(document).ready(function() {
$('.vacation').on('click', '.expand', function() {
ul
$(this).closest('.vacation')
.find('.comments') li .vacation
.fadeToggle();
a .expand
});
}); Show Comments

ul .comments
fadeIn() .comments on first click, li
fadeOut() .comments on next click.
li

4.4 Link Layover


Why does the page jump to the top?
How the Browser Handles the Click
index.html
DOCUMENT
<a href='#' class='expand'>Show Comments</a>
ul
li .vacation

a .expand
The click event will “bubble up”
Follows the link! Show Comments
to each parent node
(goes to the top of the page) ul .comments

li

li

4.4 Link Layover


The Event Object
application.js
DOCUMENT DOM TREE
$(document).ready(function() {
$('.vacation').on('click', '.expand', ul
function(event) { li .vacation
$(this).closest('.vacation') a .expand
.find('.comments')
Show Comments
.fadeToggle();
}); ul .comments
}); li

Add the event parameter li

4.4 Link Layover


event.stopPropagation()
application.js
DOCUMENT DOM TREE
$(document).ready(function() {
$('.vacation').on('click', '.expand', ul
function(event) { li .vacation
event.stopPropagation(); .expand
a
$(this).closest('.vacation')
.find('.comments') Show Comments
.fadeToggle(); ul .comments

}); li
}); li

The browser will still handle the click event but will prevent it
from “bubbling up” to each parent node.

4.4 Link Layover


event.preventDefault()
application.js
DOCUMENT DOM TREE
$(document).ready(function() {
$('.vacation').on('click', '.expand', ul
function(event) { li .vacation
event.preventDefault(); .expand
a
$(this).closest('.vacation')
.find('.comments') Show Comments
.fadeToggle(); ul .comments
}
); li
}); li

The click event will “bubble up” but the browser won’t handle it

4.4 Link Layover


We’re preventing the default action of the browser now.
level 5
Taming CSS
Separation of Concerns

To style something based on user


HTML
content
interaction, which would we use?

CSS
style

JavaScript
behavior

5.1 Taming CSS


Changing our Style DOM representation

DOCUMENT

div #vacations

ul

li .vacation

p .price

...and allow people to click


on the <li> element

Let’s make all .vacation elements clickable...

5.1 Taming CSS


Changing the Style DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).css('background-color', '#252b30');
$(this).css('border-color', '1px solid #967'); ul
});
}); li .vacation

p .price

$(this).css('background-color', '#252b30')
.css('border-color', '1px solid #967'); jQuery Object Methods
.css(<attr>, <value>)
$(this).css({'background-color': '#252b30',
'border-color': '1px solid #967'}); .css(<attr>)

Passing in a JavaScript Object as an argument is a common jQuery pattern .css(<object>)

5.1 Taming CSS


Showing the Price DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).css({'background-color': '#252b30',
'border-color': '1px solid #967'}); ul
});
}); li .vacation

p .price
$(this).find('.price').css('display', 'block');
jQuery Object Methods
$(this).find('.price').show(); .show()

Same as CSS syntax, but easier to read and understand .hide()

5.1 Taming CSS


Showing the Price DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).css({'background-color': '#252b30',
'border-color': '1px solid #967'}); ul
$(this).find('.price').show();
}); li .vacation
});
p .price
Highlights the Vacation Package and shows the price

5.1 Taming CSS


Our .vacation elements are highlighted when we click on them
Moving Styles to External CSS DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).css({'background-color': '#563',
'border-color': '1px solid #967'}); ul
$(this).find('.price').show();
}); li .vacation
});
p .price

application.css
Can we move these to a CSS stylesheet?
.highlighted { $(this).addClass('highlighted');
background-color: #563;
border-color: 1px solid #967;
}
.highlighted .price {
display: block;
}

5.1 Taming CSS


Moving Styles to External CSS DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).addClass('highlighted');
}); ul
});
li .vacation
It’s now much easier to manipulate with external CSS styles
p .price
application.css
.highlighted {
background-color: #563;
border-color: 1px solid #967;
}
.highlighted .price {
display: block;
}

5.1 Taming CSS


Moving Styles to External CSS DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).addClass('highlighted');
}); ul
});
li .vacation
We can only show price, but how would we hide price?
p .price

$(this).toggleClass('highlighted');
jQuery Object Methods
Adds the class if $(this) doesn’t have it, removes it if $(this) already has it
.toggleClass()

.addClass(<class>)

.removeClass(<class>)

5.1 Taming CSS


Our refactored page still works, and will be much easier to maintain
Challenges

5.1 Taming CSS


Animation
What can we do to add a bit more movement to this?
Adding Movement DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
}); ul
});
li .vacation

p .price
$(this).css({'top': '-10px'});

The box will jump up 10 px jQuery Object Methods


$(this).animate({'top': '-10px'}); .animate(<object>)
Takes in a JavaScript object
similar to the .css() method

5.2 Animation
Adding Movement DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
$(this).animate({'top': '-10px'}); ul
});
}); li .vacation

Will adjust a CSS property pixel by pixel in order to animate it p .price

5.2 Animation
Our animation can slide up but not slide down
Moving Back Down DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
$(this).animate({'top': '-10px'}); ul
});
}); li .vacation

p .price
How do we set ‘top’ to ‘0px’ if a second click occurs?
if(<vacation has the class highlighted>) {
// animate the vacation up
} else {
// animate the vacation back down
}

“If statements” allow your code to make decisions at runtime

5.2 Animation
Moving Back Down DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
if(<vacation has the class highlighted>) { ul
$(this).animate({'top': '-10px'});
} else { li .vacation
$(this).animate({'top': '0px'}); p .price
}
});
}); jQuery Object Methods
.hasClass(<class>)
$(this).hasClass('highlighted');
true

Returns true or false

5.2 Animation
Moving Back Down DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
if( $(this).hasClass('highlighted') ) { ul
$(this).animate({'top': '-10px'});
} else { li .vacation
$(this).animate({'top': '0px'}); p .price
}
});
});

Our vacation package will move up and down

5.2 Animation
Could we speed this up a little? Our customers don’t have all day.
Changing the Speed
$(this).animate({'top': '-10px'});
We can optionally pass in the speed as a
second argument to animate()
$(this).animate({'top': '-10px'}, 400);

$(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 milliseconds

5.2 Animation
Moving Back Down DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
if($(this).hasClass('highlighted')) { ul
$(this).animate({'top': '-10px'}, 'fast');
} else { li .vacation
$(this).animate({'top': '0px'}, 'fast');
p .price
}
});
});

And with this we now have specific speeds for our animation

5.2 Animation
Our jQuery animation is now using a ‘fast’ speed
The Next Step with CSS Animations DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
if($(this).hasClass('highlighted')) { ul
$(this).animate({'top': '-10px'}, 'fast');
} else { li .vacation
$(this).animate({'top': '0px'}, 'fast');
p .price
}
});
});

Isn’t this still styling? Shouldn’t it be inside of a stylesheet?

5.2 Animation
Animation Duration DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
}); ul
});
li .vacation
application.css
p .price
.vacation {
transition: top 0.2s;
}
.highlighted {
top: -10px;
}

Will only work with browsers that implement CSS transitions

5.2 Animation
Working with Modern Browsers DOM representation
application.js
DOCUMENT
$(document).ready(function() {
$('#vacations').on('click', '.vacation', function() { div #vacations
$(this).toggleClass('highlighted');
}); ul
});
li .vacation
application.css
p .price
.vacation {
-moz-transition: top 0.2s;
-o-transition: top 0.2s; Unlike jQuery, with CSS we have
-webkit-transition: top 0.2s; to account for specific browsers
transition: top 0.2s;
}
.highlighted {
top: -10px;
}

5.2 Animation
CSS Animations are a huge topic, but worth looking into

You might also like