Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Chapter10 JavaScript3ExtendingJavaScriptwithjQuery

The document discusses chapters in a book about extending JavaScript with jQuery. Chapter 10 covers jQuery foundations, event handling, DOM manipulation, effects and animation, AJAX, and file transmission.

Uploaded by

boratok234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Chapter10 JavaScript3ExtendingJavaScriptwithjQuery

The document discusses chapters in a book about extending JavaScript with jQuery. Chapter 10 covers jQuery foundations, event handling, DOM manipulation, effects and animation, AJAX, and file transmission.

Uploaded by

boratok234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

JavaScript 3: Extending

JavaScript
with jQuery

Chapter 10

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


© 2017 Pearson
Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2 nd
Ed.
http://www.funwebdev.com
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
A popular framework

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Including jQuery

Use a Content Delivery Network (CDN)

<script src="http://code.jquery.com/jquery-3.1.0.min.js">
</script>

Use a failsafe in case the CDN is down

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
jQuery Selector

Remember getElementByID()…
• The power of jQuery resides in the function named
jQuery().
• There’s also an alias for this function named $() .
• You can combine CSS selectors with the $()
notation to select DOM objects that match CSS
attributes

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
jQuery Selector

/* selecting using regular JavaScript */


var node = document.getElementById("here");
var link = document.querySelectorAll("ul li");
/* equivalent selection using jQuery */
var node = $("#here");
var link = $("ul li");
• The $() function always returns a set of results

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Basic Selectors

• $("*")—Universal selector matches all elements (and is slow).


• $("tag")—Element selector matches all elements with the
given element name.
• $(".class")—Class selector matches all elements with the
given CSS class.
• $("#id")—Id selector matches all elements with a given HTML
id attribute.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Some examples

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Advanced Selectors (Go back to Chapter 4 in CSS for a refresher)

• Attribute Selector
• Pseudo-Element Selector
• Contextual Selector
• jQuery Filters
• Form Selectors

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
jQuery's content filter selection

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Common element Manipulations - HTML attributes

• We can both set and get an attribute value by using the attr()
method.
// link is assigned the href attribute of the first <a> tag

var link = $("a").attr("href");

// change all links in the page to http://funwebdev.com

$("a").attr("href","http://funwebdev.com");

// change the class for all images on the page to fancy

$("img").attr("class","fancy");

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Common element Manipulations - HTML properties

• The prop() method is the preferred way to retrieve and set


the value of a property.

<input class="meh" type="checkbox" checked="checked">

var theBox = $(".meh");


theBox.prop("checked"); // evaluates to TRUE

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
jQuery Foundations
Common element Manipulations – Changing CSS

• jQuery provides the extremely intuitive css() method.

var color = $("#element").css("background-color"); // get the color


$("#element").css("background-color", "red"); // set color to red

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Event Handling in jQuery

Just like JavaScript, jQuery supports creation and


management of listeners/handlers for JavaScript
events.
While pure JavaScript uses the addEventListener()
method, jQuery has on() and off() methods as well as
shortcut methods to attach events.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Event Handling in jQuery
Binding and Unbinding Events

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Event Handling in jQuery
Page Loading

$(document).ready(function() {
// set up listeners knowing page loads before this runs
$("#example").click(function () {
$("#message").html("you clicked");
});
});
Or the even simpler
$(function () {
...
});

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Creating Nodes

// pure JavaScript way

var jsLink = document.createElement("a");


jsLink.href = "http://
www.funwebdev.com";
jsLink.innerHTML = "Visit Us";
jsLink.title = "JS";

// jQuery version 1

var link1 = $('<a href="http://funwebdev.com"


title="jQuery">Visit Us</a>');

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Creating Nodes

// jQuery version 2
var link2 = $('<a></a>');
link2.attr("href","http://funwebdev.com");
link2.attr("title","jQuery verbose");
link2.html("Visit Us");

// version 3
$('<a>', {
href: 'http://funwebdev.com',
title: 'jQuery',
text: 'Visit Us'
});

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Adding DOM Elements

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Wrapping Existing DOM in New Tags

• Wrap all elements matched by a selector within a new


element using wrap().

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Wrapping Existing DOM in New Tags

<div class="external-links">
<div class="gallery">Uffuzi Museum</div>
<div class="gallery">National Gallery</div>
<div class="link-out">funwebdev.com</div>
</div>

$(".gallery").wrap('<div class="galleryLink"><div>');

<div class="external-links">
<div class="galleryLink">
<div class="gallery">Uffuzi Museum</div>
</div>
<div class="galleryLink">
<div class="gallery">National Gallery</div>
</div>
<div class="link-out">funwebdev.com</div>
</div>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
DOM Manipulation
Wrapping Existing DOM in New Tags

<div class="external-links">
<div class="gallery">Uffuzi Museum</div>
<div class="gallery">National Gallery</div>
<div class="link-out">funwebdev.com</div>
</div>
$(".gallery").wrap(function() {
return "<div class='galleryLink' title='Visit " + $(this).html() + "'></div>";
});

<div class="external-links">
<div class="galleryLink" title="Visit Uffuzi Museum">
<div class="gallery">Uffuzi Museum</div>
</div>
<div class="galleryLink" title="Visit National Gallery">
<div class="gallery">National Gallery</div>
</div>
<div class="link-out">funwebdev.com</div>
</div>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Show() and fadeIn()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Using slide()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Raw Animation

$("#box").animate({left: '495px'});
• Describes a final state in CSS.
• The state before defines where the animations
starts.
• Animate() has many parameters including:
• Duration
• Step
• Done
• …

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Raw Animation

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Easing Functions

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Effects and Animation
Easing Functions

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Asynchronous JavaScript with XML (AJAX)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Making Asynchronous Requests

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Synchronous example

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Asynchronous example – what's changed?

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Making Asynchronous requests – load()

Easy shortcut functions like load()

$("#timeDiv").load("currentTime.php");
• Asynchronously calls currentTime.php and puts the
returned content into the selected div with id
timeDiv

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Making Asynchronous requests - GET

Easy shortcut functions .get()

$.get("serviceTravelCountries.php?name=Italy");

Note that the $ symbol is followed by a dot.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Making Asynchronous requests – GET formal

jQuery.get ( url [, data ] [, success([data, textStatus, jqXHR]) ]


[, dataType ] )
• url is a string that holds the location to send the request.
• data is an optional parameter that is a query string or a JavaScript
object literal.
• success(data,textStatus,jqXHR) is an optional callback function
• data holding the body of the response as a string.
• textStatus holding the status of the request (i.e., “success”).
• jqXHR holding a jqXHR object

• dataType is an optional parameter to hold the type of data


expected

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
The jqXHR Object

• $.get() requests made by jQuery return a jqXHR object


• jqXHR objects implement the methods
• done(),
• fail(), and
• always(),

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
The jqXHR Object

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
The POST Method

jQuery handles POST almost as easily as GET, with the


need for an added field to hold our data.
$.get("serviceTravelCities.php", param)
to
$.post("serviceTravelCities.php", param)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
The POST Method – form serialization

The serialize() method can be called on a DOM form


element to encode it into a query string
var postData = $("#someForm").serialize();
$.post("formHandler.php", postData);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Complete Control over AJAX

Over 30 fields to customize control. Here we add headers

$.ajax({ url: "vote.php",


data: $("#voteForm").serialize(),
async: true,
type: post,
headers: {"User-Agent" : "Homebrew Vote Engine",
"Referer": "http://funwebdev.com"
}
});

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
AJAX
Cross-Origin Resource Sharing

cross-origin resource sharing described in greater


detail in Chapter 18.
• a way by which some malicious software can gain
access to the content of other web pages you are
surfing despite the scripts being hosted on another
domain
• sharing content legitimately between two domains
becomes harder
• images.funwebdev.com and www.funwebdev.com
are considered different origins
• Access-Control-Allow-Origin header

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Asynchronous File Transmission
The FormData Interface

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Asynchronous File Transmission
The FormData Interface

function uploadFile () {
// get the file as a string
var formData = new FormData($("#fileUpload")[0]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
xhr.open('POST', 'upload.php', true);
xhr.send(formData); // actually send the form data
function transferComplete(evt) { // stylized upload complete
$("#progress").css("width","100%");
$("#progress").html("100%");
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Asynchronous File Transmission
Appending Files to a POST

var allFiles = $(":file")[0].files;


for (var i=0;i<allFiles.length;i++) {
formData.append('images[]', allFiles[i]);
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Chapter 10
1 jQuery
Foundations 2 Event Handling
in jQuery

3 DOM
Manipulation 4 Effects and
Animation

Asynchronous
5 AJAX
6 File
Transmission

7
Summary

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Summary
Key Terms

Animation cross-origin graceful


resource degredation
Asynchronous
JavaScript sharing (CORS) jQuery
with XML (AJAX) easing function jqXHR
content delivery filters library
network
framework progressive
(CDN) enhancement
FormData
content filters

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Summary
Questions?

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.

You might also like