Professional Documents
Culture Documents
jQuery
Lesson 01: JQuery
Fundamentals
Lesson Objectives
jQuery Introduction
Why jQuery?
About jQuery.com
Using jQuery
Using Content Delivery Network(CDN)
jQuery Selector
jQuery Effects
jQuery Events
1.1: jQuery Introduction
jQuery Introduction
jQuery is a JavaScript library (single file)
jQuery is a lightweight, "write less, do more", JavaScript library
It supports cross browser
Select HTML elements
Handle Events
Animate HTML elements
Make Ajax calls
1000’s of plug-ins available
The purpose of jQuery is to make it much easier to use
JavaScript on your website.
1.2: Why jQuery?
Why jQuery?
JavaScript is great for a lot of things especially manipulating the
DOM but it’s pretty complex stuff.
jQuery abstracts away a lot of the complexity involved in dealing
with the DOM, and makes creating effects super easy.
It can locate elements with a specific class
It can apply styles to multiple elements
It solves the cross browser issues
It supports method chaining
It makes the client side development very easy
1.3. About jQuery.com
$(document).ready(function(){
});
1.4. Using jQuery
Using jQuery
<html>
<head>
<title>Test jQuery</title>
<script type="text/javascript" src="jquery-1.12.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Hi'); });
</script>
</head>
<body>
jQuery Enabled
</body>
</html>
1.4. Using jQuery
Document.ready
$(document).ready
• Is specific event to jQuery
• Occurs after the HTML document has been loaded
• Is jQuery event that is fired when DOM is loaded, so it’s fired when the
document structure is ready.
• Ex -
$(document).ready(function(){ });
Demo
jQuery
1.5: Content Delivery Network(CDN)
Introduction to selectors
jQuery uses same CSS selectors to style and manipulate
elements on the page.
CSS selectors select elements to add style whereas jQuery
selectors select elements to add behavior.
Selectors allow page elements to be selected.
Single or Multiple elements are supported.
A Selector identifies an HTML element / tag that will be
manipulated with jQuery Code.
Selector Syntax
• $(selectorExpression)
• jQuery(selectorExpression)
2.2. Using Different JQuery Selectors
Tag Selector
Selecting single tag takes the following syntax
• $(‘p’) – selects all <p> elements
• $(‘a’) – selects all <a> elements
Id Selector
It is used to locate the DOM element very fast.
Use the # character to select elements by ID
Class Selector
Use the ( . ) character to select elements by class name
jQuery Selectors
jQuery Event
All the different visitor's actions that a web page can respond to
are called events.
An event represents the precise moment when something
happens.
Examples:
• moving a mouse over an element
• selecting a radio button
• clicking on an element
4.2. jQuery Event Model Benefits
jQuery Events
jQuery Events
Summary
Tree of Objects
JS Output Example1
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
Using console.log()
For debugging purposes, you can call the console.log() method
in the browser to display data.
<script>
console.log(5 + 6);
</script>
When to Use?
• Always declare JavaScript variables with var, let, or const.
• The let and const keywords were added to JavaScript in 2015.
• If you want your code to run in older browsers, you must use var.
• If you want a general rule: always declare variables with const.
• If you think the value of the variable can change, use let.
– const price1 = 5;
– const price2 = 6;
– let total = price1 + price2;
• <script>
• let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• document.getElementById("demo").innerHTML = text.length;
• </script>
Function Invocation
• The code inside the function will execute when
"something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>
<body>
<button
onclick="document.getElementById('demo').innerHTM
L=Date()">The time is?</button>
<p id="demo"></p>
</body>
Try this
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
} </script>
<p id="demo"></p>
const cars = [
"Saab",
"Volvo",
"BMW"
];
Accessing Array Elements
• const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0]; //Saab
<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe",
age:46};
document.getElementById("demo").innerHTML =
person.firstName;
</script>
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat",
"Audi"];
let text = "";
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML
Workshop on Advanced JavaScript & = text;
Frameworks
</script> JS
The For In Loop
• for (key in object) {
// code block to be executed
}
• const person = {fname:"John", lname:"Doe",
age:25};
let text = "";
for (let x in person) {
text += person[x];
}
• Output for text is John Doe 25
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
function myDisplayer(some) {
document.getElementById("demo").innerHTML =
some;
}
[cont..]
School of Engineering
CSE3150 – Front-end Full Stack
1
Development
Module 2 - Syllabus
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
Refer Pgm1
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
.menu {
width: 25%;
float: left;
}
.main {
width: 75%;
float: left;
}
Refer Pgm2
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
Refer Pgm3
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates
• Bootstrap 5 uses HTML elements and CSS properties that require the
HTML5 doctype.
• Always include the HTML5 doctype at the beginning of the page,
along with the lang attribute and the correct title and character set
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
</head>
</html>
– The initial-scale=1 part sets the initial zoom level when the page
is first loaded by the browser.
Refer Pgm4
• Refer Pgm6
• Select menus are used if you want to allow the user to pick
from multiple options.
• To style a select menu in Bootstrap 5, add the .form-select
class to the <select> element:
• Select menus are used if you want to allow the user to pick
from multiple options.
• To style a select menu in Bootstrap 5, add the .form-select
class to the <select> element:
• Open-source. View source is allowed, and anyone can view the code source
written for Ajax, which makes it less secure compared to other technologies
• Search Engines cannot index Ajax pages can not be indexed by Google as
well as other search engines
• The usage of Ajax can cause difficulties for your web pages to debug as well
as make them prone to possible security issues in the future
• Most importantly, Ajax has a considerable dependency on JavaScript, so
only browsers that support Javascripts or XMLHttpRequest can use pages
with Ajax techniques
• Users will find it challenging to bookmark a specific state of the application
due to the dynamic web page
Why use Ajax?
Client/Server Apps:
• Dynamic data
• Static forms, controls, code, etc
• Efficient, but not flexible
Traditional Web Apps:
• Dynamic data
• Dynamic forms, controls, code, etc
• Flexible, but inefficient, and noticeably slow
Ajax Apps:
• Dynamic data
• Static or dynamic forms, controls, code, etc
• Best of both worlds
Why use Ajax?
Multithreaded data retrieval from Web servers
Pre-fetch data before needed
Progress indicators
Appearance of speed
Avoids need for setTimeout()
Less bandwidth required; less server load
Reload partial page, not entire page
Load data only, not even partial page
Synchronous web communication
CS380 10
Web applications and Ajax
• web application: a dynamic web site that mimics the feel of a
desktop app
• presents a continuous user experience rather than disjoint pages
• examples: Gmail, Google Maps, Google Docs and Spreadsheets, Flickr, A9
CS380 11
Web applications and Ajax
• Ajax: Asynchronous JavaScript and XML
• not a programming language; a particular way of using JavaScript
• downloads data from a server in the background
• allows dynamically updating a page without making the user wait
• avoids the "click-wait-refresh" pattern
• Example: Google Suggest
CS380 12
Asynchronous web communication
CS380 13
XMLHttpRequest (and why we won't use it)
CS380 14
XMLHttpRequest (and why we won't use it)
• sounds great!...
• ... but it is clunky to use, and has various browser incompatibilities
• Prototype provides a better wrapper for Ajax, so we will use that
instead
CS380 15
A typical Ajax request
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object
3. XMLHttpRequest object requests page from server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires an event when data arrives
• this is often called a callback
• you can attach a handler function to this event
6. your callback event handler processes the data and
displays it
16
A typical Ajax request
CS380 17
Prototype's Ajax model
new Ajax.Request("url",
{
option : value,
option : value,
...
option : value
}
); JS
CS380 19
Prototype Ajax methods and properties
event description
onSuccess request completed successfully
onFailure request was unsuccessful
request has a syntax error,
onException
security error, etc.
CS380 20
Basic Prototype Ajax template
property description
the request's HTTP error code
status
(200 = OK, etc.)
statusText HTTP error code text
the entire text of the fetched
responseText
page, as a String
the entire contents of the
responseXML fetched page, as an XML DOM
tree (seen later)
function handleRequest(ajax) {
alert(ajax.responseText);
} JS
21
XMLHttpRequest security restrictions
22
Handling Ajax errors
new Ajax.Request("url",
{
method: "get",
onSuccess: functionName,
onFailure: ajaxFailure,
onException: ajaxFailure
}
);
...
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" + "\n\nServer
status:\n" + ajax.status + " " + ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
• for user's (and developer's)
throw exception; benefit, show an error
message
} if a request fails
} JS
CS380 23
Debugging Ajax code
• Net tab shows each request, its parameters, response, any errors
• expand a request with + and look at Response tab to see Ajax result
24
Creating a POST request
new Ajax.Request("url",
{
method: "post", // optional
parameters: { name: value, name: value, ..., name:
value },
onSuccess: functionName,
onFailure: functionName,
onException: functionName
}
); JS
CS380 25
Creating a POST request
• Ajax.Request can also be used to post data to a web server
• method should be changed to "post" (or omitted; post is
default)
• any query parameters should be passed as a parameters
parameter
• written between {} braces as a set of name : value pairs (another
anonymous object)
• get request parameters can also be passed this way, if you like
CS380 26
Prototype's Ajax Updater
new Ajax.Updater(
"id",
"url",
{
method: "get"
}
); JS
CS380 27
What Advances have Been Made to Ajax?
• JavaScript is the client-side programming language and XML is a markup language
to define data.
• JSON is another markup language to define data. JSON (JavaScript Object
Notation) is much easier to use with JavaScript than XML.
• When it comes to Ajax and JavaScript, JSON Web Services are replacing XML Web
Services.
• Another major advance to JavaScript and Ajax is the JavaScript object library
called jQuery.
• This free, open-source software is a wrapper around JavaScript.
• jQuery is used to easily write client-side JavaScript to navigate and manipulate a
page and make asynchronous Ajax callbacks.
• By using jQuery and JSON Web Services, Ajax callbacks have become standard
programming practices for designing and developing web applications.
AJAX Application Example
Online test
Many multiple choice questions
All questions are displayed on one page
After the user answers one question, the correct answer and
explanation about why the user answer is wrong is shown on the page
For all already-answered questions, their correct answers and
explanations are always shown on the page
Pure sever-side solution using conventional web application
For each question answer submission, the whole page with most of repeated data sent to
the browser
Pure client-side solution using conventional JavaScript.
The user can read JavaScript source code to view what is correct answer
Large amount of explanation data will be carried by the JavaScript codeAJAX solution
After the user answers a question, use XmlHttpRequest to ask the server to send the
correct answer and explanation. Display the correct answer and explanation received from
the server.