You are on page 1of 212

Introduction to

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

How webpage works


DOM (Document Object Model)
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

jquery.com (Official Website for jQuery)


jQuery Syntax
syntax is: $(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
Example :
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Jquery Syntax

$(document).ready(function(){

// jQuery methods go here...

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

Content Delivery Network(CDN)


Script can be also accessible from
• Microsoft - http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.3.min.js
• jQuery - http://code.jquery.com/jquery-1.12.3.min.js
• Google - http://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js

A CDN short for Content Delivery Network distributes static


content across servers. When a user’s browser resolves the URL
for these files, their download will automatically target the closest
available server in the network.
2.1 : Introduction to Selectors

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

To reference multiple tags, use the ( , ) to separate the elements


• $(‘p, a, span’) - selects all paragraphs, anchors and span elements
2.2. Using Different JQuery Selectors

Id Selector
It is used to locate the DOM element very fast.
Use the # character to select elements by ID

• $(‘#myID’) – selects <div id=“myid”> element


2.2. Using Different JQuery Selectors

Class Selector
Use the ( . ) character to select elements by class name

• $(‘.myclass’) - selects <div class=“myclass”> element

To reference multiple tags, use the ( , ) character to separate the


class name.
• $(‘.blueDiv,.redDiv’) - selects all the elements containing the class blueDiv
and redDiv
Tag names can be combined with elements name as well.
• $(‘div.myclass’) – selects only <div> tags with class=“myclass”
Demo

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

Mouse Events Keyboard Form Events Document/Window


Events Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload


Demo

jQuery Events
Summary

jQuery is a cross browser java script library


Available at http://www.jquery.com
The ready() function detects when the DOM
hierarchy is loaded
Window.load event fires when the DOM and all the
content on the page is fully loaded.
Review Question

Which sign does jQuery use as a shortcut for jQuery?


• $ Sign
• % Sign
• # Sign
• ? Sign

Which jQuery function is used to prevent code from


running, before the document is finished loading?
• $(document).load()
• $(document).ready()
• $(body).onload()
Javascript

Workshop on Advanced JavaScript & Frameworks


What is Javascript?
• a lightweight programming language
("scripting language")
JavaScript makes web pages more dynamic and user-friendly so that
they respond to visitors' actions.
OR, to put it another way, JavaScript makes web pages interactive.

– used to make web pages interactive


– insert dynamic text into HTML (ex: user name)
– react to events (ex: page load user click)
– perform calculations on user's computer (ex: form
validation)

Workshop on Advanced JavaScript &


Frameworks
Linking to a JavaScript file: script

<script src="filename" type="text/javascript">


</script>

• script tag should be placed in HTML page's head


• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body
or head (like CSS)

Workshop on Advanced JavaScript &


Frameworks
Event-driven programming

Workshop on Advanced JavaScript &


Frameworks
Event handlers

<element attributes onclick="function();">...

<button onclick="myFunction();">Click me!</button>

Workshop on Advanced JavaScript &


Frameworks
The HTML DOM (Document Object Model)

Tree of Objects

Workshop on Advanced JavaScript &


Frameworks
Document Object Model (DOM)
• JavaScript can change all the HTML
elements in the page
• JavaScript can change all the HTML
attributes in the page
• JavaScript can change all the CSS
styles in the page
• JavaScript can remove existing HTML
elements and attributes
• JavaScript can add new HTML elements
and attributes
• JavaScript can react to all existing
HTML events in the page
• JavaScript can create new HTML events
in the page

Workshop on Advanced JavaScript &


Frameworks
Accessing elements:
document.getElementById

 document.getElementById returns the DOM object for an


element with a given id
 can change the text inside most elements by setting the
innerHTML property
 can change the text in form controls by setting the value
property

Workshop on Advanced JavaScript &


Frameworks
Accessing elements:
document.getElementById
• In the DOM, all HTML elements are defined as
objects.
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "
Hello World!";
</script>
</body>
The innerHTML property is useful for getting or replacing the content of
HTML elements.

JS Output Example1

Workshop on Advanced JavaScript &


Frameworks
Finding HTML Elements

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Workshop on Advanced JavaScript &


Frameworks
Accessing elements:
document.getElementById
var name = document.getElementById("id");

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" />
</body>
<script>
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
}
</script>

Workshop on Advanced JavaScript & Frameworks


Changing element style: element.style

Attribute Property or style object

color color

padding padding

background-color backgroundColor

border-top-width borderTopWidth

Font size fontSize

Font famiy fontFamily

Workshop on Advanced JavaScript &


Frameworks
function changeText() {

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
}

Workshop on Advanced JavaScript &


Frameworks
JavaScript Output
JavaScript can "display" data in different ways:

• Writing into an HTML element, using innerHTML.


• Writing into the HTML output using
document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using
console.log().

Workshop on Advanced JavaScript &


Frameworks
Using innerHTML
The id attribute defines the HTML element. The innerHTML
property defines the HTML content:
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 +
6;
</script>
</body>
</html

Workshop on Advanced JavaScript &


Frameworks
Using document.write()
<script>
document.write(5 + 6);
</script>
<button type="button" onclick="document.write(5 +
6)">
Try it</button>

Workshop on Advanced JavaScript &


Frameworks
Displaying text
• The document.write() method writes a string of text
to the browser

<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>

Workshop on Advanced JavaScript &


Frameworks
Using window.alert()
<script>
window.alert(7 +12);
</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>

Workshop on Advanced JavaScript &


Frameworks
Workshop on Advanced JavaScript &
Frameworks
Comments in JavaScript
• Two types of comments
– Single line
• Uses two forward slashes (i.e. //)
– Multiple line
• Uses /* and */

Workshop on Advanced JavaScript &


Frameworks
JavaScript Primitive Datatypes
• Boolean: true and false
• Number: 64-bit floating point
– Similar to Java double and Double
– No integer type
– Special values NaN (not a number) and Infinity
• String: sequence of zero or more Unicode chars
– No separate character type (just strings of length 1)
– Literal strings using ' or " characters (must match)
• Special objects: null and undefined

Workshop on Advanced JavaScript &


Frameworks
4 Ways to Declare a JavaScript Variable
• Using var
• Using let
• Using const
• Using nothing

Workshop on Advanced JavaScript &


Frameworks
Variables

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS
• variables are declared with the var keyword (case
sensitive)
• types are not specified, but JS does have types
("loosely typed")
– Number, Boolean, String, Array, Object, Function, Null,
Undefined
– can find out a variable's type by calling typeof()

Workshop on Advanced JavaScript &


Frameworks
– let x = 5;
– let y = 6;
– let z = x + y;

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;

Workshop on Advanced JavaScript &


Frameworks
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");

Workshop on Advanced JavaScript &


Frameworks
Special values: null and undefined

var ned = null;


var benson = 9;
var caroline;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
 undefined : has not been declared, does not exist
 null : exists, but was specifically assigned an empty or
null value
 Why does JavaScript have both of these?

Workshop on Advanced JavaScript &


Frameworks
Operators

• Refer all operators you studied in java

Workshop on Advanced JavaScript &


Frameworks
JavaScript Strings
• <p>The length of the string is:</p>
• <p id="demo"></p>

• <script>
• let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• document.getElementById("demo").innerHTML = text.length;
• </script>

Workshop on Advanced JavaScript &


Frameworks
JavaScript Functions
function name (parameter1, parameter2,….) {
// code to be executed
}

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)

Workshop on Advanced JavaScript &


Frameworks
Example 1
<p id="demo"></p>

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>

Workshop on Advanced JavaScript &


Frameworks
Example 2
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>

Workshop on Advanced JavaScript &


Frameworks
Popup boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

Workshop on Advanced JavaScript &


Frameworks
JavaScript Objects
• Real Life Objects, Properties, and Methods
• In real life, a student is an object.
• Student can have properties name,
roll_no.,marks,phone_num, age…
• Student can have methods to operate on properties
like Calcualte_cgpa(), diplayInfo()….
• All student have same properties, values may
change
• Assume car is an object

Workshop on Advanced JavaScript &


Frameworks
• let car = "Fiat";
• Objects are variables too. But objects can contain
many values.
• const car = {type:"Fiat", model:"500",
color:"white"};
• The values are written as name:value pairs
(name and value separated by a colon).

Workshop on Advanced JavaScript &


Frameworks
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

Workshop on Advanced JavaScript &


Frameworks
JavaScript Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
HTML Events
• An HTML event can be something the browser does, or
something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked

Workshop on Advanced JavaScript &


Frameworks
• HTML allows event handler attributes, with JavaScript
code, to be added to HTML elements.
<element event='some JavaScript’>

<body>
<button
onclick="document.getElementById('demo').innerHTM
L=Date()">The time is?</button>
<p id="demo"></p>
</body>

Workshop on Advanced JavaScript &


Frameworks
<body>
<h2>JavaScript HTML Events</h2>
<button onclick="this.innerHTML=Date()">The time
is?</button>
</body>

Try this
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
} </script>
<p id="demo"></p>

Workshop on Advanced JavaScript &


Frameworks
JavaScript Arrays
Syntax:
• const array_name = [item1, item2, ...];

const cars = [
"Saab",
"Volvo",
"BMW"
];
Accessing Array Elements
• const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0]; //Saab

Workshop on Advanced JavaScript &


Frameworks
• Objects use names to access its "members".
• In this example, person.firstName returns John:

<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe",
age:46};
document.getElementById("demo").innerHTML =
person.firstName;
</script>

Workshop on Advanced JavaScript &


Frameworks
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length; //4
Looping Array Elements
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
document.getElementById("demo").innerHTML = text;
function myFunction(value) {
text += "<li>" + value + "</li>";
} </script>

Workshop on Advanced JavaScript &


Frameworks
Adding elements to array
• const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon");
OR
• const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon";

• JavaScript does not support associative arrays.


• You should use objects when you want the element names to be strings (text).
• You should use arrays when you want the element names to be numbers.

Workshop on Advanced JavaScript &


Frameworks
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef

 array serves as many data structures: list, queue, stack, ...


 methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is removed

Workshop on Advanced JavaScript &


Frameworks
if/else statement (same as Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS

 identical structure to Java's if/else statement


 JavaScript allows almost anything as a condition

Workshop on Advanced JavaScript &


Frameworks
for loop (same as Java)
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS

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

Workshop on Advanced JavaScript &


Frameworks
The For Of Loop
• for (variable of iterable) {
// code block to be executed
}
• const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
} // BMW Volvo Mini

let language = "JavaScript";


let text = "";
for (let x of language) {
text += x ; } // JavaScript

Workshop on Advanced JavaScript &


Frameworks
while loops (same as Java)

while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also behave as in


Java

Workshop on Advanced JavaScript &


Frameworks
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS

• methods: charAt, charCodeAt, fromCharCode, indexOf,


lastIndexOf, replace, split, substring, toLowerCase,
toUpperCase
– charAt returns a one-letter String (there is no char type)
• length property (not a method as in Java)
• Strings can be specified with "" or ''
• concatenation with + :
– 1 + 1 is 2, but "1" + 1 is "11"

Workshop on Advanced JavaScript &


Frameworks
JavaScript Callbacks

• A callback is a function passed as an argument to another


function
• This technique allows a function to call another function
• A callback function can run after another function has finished
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum; //return to result
}
let result = myCalculator(5, 5); //fncall
myDisplayer(result); // fn call

Workshop on Advanced JavaScript &


Frameworks
JavaScript Promises
"Producing code" is code that can take some time
"Consuming code" is code that must wait for the result
A Promise is a JavaScript object that links producing code and
consuming code
A JavaScript Promise object contains both the producing code
and calls to the consuming code:
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then (
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);

Workshop on Advanced JavaScript &


Frameworks
A JavaScript Promise object can be:
• Pending -- (working), the result is undefined.
• Fulfilled -- the result is a value.
• Rejected -- the result is an error object.

function myDisplayer(some) {
document.getElementById("demo").innerHTML =
some;
}
[cont..]

Workshop on Advanced JavaScript &


Frameworks
let myPromise = new Promise(function(myResolve, myReject)
{
let x = 0;
// The producing code (this may take some time)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
// change x=5 and Try

Workshop on Advanced JavaScript &


Frameworks
JavaScript Async
• async makes a function return a Promise
• await makes a function wait for a Promise
async function myFunction() {
return "Hello";
}
Is same as
function myFunction() {
return Promise.resolve("Hello");
}

Workshop on Advanced JavaScript &


Frameworks
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
async function myFunction() {return "Hello";}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>

Workshop on Advanced JavaScript &


Frameworks
• The await keyword can only be used inside an async function.
• The await keyword makes the function pause the execution and
wait for a resolved promise before it continues:
<h1 id="demo"></h1>
<script>
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve(“Welcome!!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
</script>

Workshop on Advanced JavaScript &


Frameworks
Waiting for a Timeout
<h1 id="demo"></h1>
<script>
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve(“Welcome !!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
</script>

Workshop on Advanced JavaScript &


Frameworks
Workshop on Advanced JavaScript &
Frameworks
CSE3150 – Front-end Full Stack Development

Department of Computer Science Engineering

School of Engineering
CSE3150 – Front-end Full Stack
1
Development
Module 2 - Syllabus

[Lecture-5 Hrs, Practical-6 Hrs, Application]


BootStrap for Responsive Web Design;

JavaScript – Core syntax, HTML DOM, objects, classes, Async;

Ajax and jQuery Introduction.

CSE3150 – Front-end Full Stack


2
Development
Module 2 - Syllabus

BootStrap for Responsive Web Design

CSE3150 – Front-end Full Stack


3
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


4
Development
Responsive Web Design

• The process of building websites & online portals with a


stronger CX/UX (customer/user experience) optimal view
solutions on a web page with the best browser compatibility
that can run & operate in a variety of devices is known as
responsive web design.

CSE3150 – Front-end Full Stack


5
Development
Responsive Web Design

• Responsive web design makes your web page look good on


all devices.
• Responsive web design uses only HTML and CSS.
• Responsive web design is not a program or a JavaScript.
• Web pages can be viewed using many different devices:
desktops, tablets, and phones.
• Your web page should look good, and be easy to use,
regardless of the device.

CSE3150 – Front-end Full Stack


6
Development
Responsive Web Design
• Web pages should not leave out information to fit smaller
devices, but rather adapt its content to fit any device.

• It is called responsive web design when you use CSS and


HTML to resize, hide, shrink, enlarge, or move the content to
make it look good on any screen.

CSE3150 – Front-end Full Stack


7
Development
Responsive Web Design
• Responsive web design is a suitable, robust, & fast solution
that enables lesser efforts from the developers’ end.
• Ethan Marcotte first described responsive web design as
responding to the needs of people and the devices they are
utilizing.
• Depending on the size and capabilities of the gadget, the
layout alters.
• E.g.: With a phone, consumers might see content presented
in a single column perspective; on a tablet, the same
content might be presented in two columns.

CSE3150 – Front-end Full Stack


8
Development
Responsive Web Design - Example

Refer Pgm1

CSE3150 – Front-end Full Stack


9
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


10
Development
Viewport
• The viewport is the user's visible area of a web page.

• The viewport varies with the device, and will be smaller on a


mobile phone than on a computer screen.

CSE3150 – Front-end Full Stack


11
Development
Setting The Viewport

• HTML5 introduced a method to let web designers take control over


the viewport, through the <meta> tag.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
• This gives the browser instructions on how to control the page's
dimensions & scaling.
• The width=device-width part sets the width of the page to follow
the screen-width of the device (which will vary depending on the
device).
• The initial-scale=1.0 part sets the initial zoom level when the page
is first loaded by the browser.

CSE3150 – Front-end Full Stack


12
Development
Setting The Viewport
Without the viewport meta tag With the viewport meta tag

CSE3150 – Front-end Full Stack


13
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


14
Development
Grid View

• Many web pages are based on a grid-view, which means that


the page is divided into columns
• Using a grid-view is very helpful when designing web pages.
• It makes it easier to place elements on the page.
• A responsive grid-view often has 12 columns, and has a
total width of 100%, and will shrink & expand as you resize
the browser window.

CSE3150 – Front-end Full Stack


15
Development
Building a Responsive Grid-View
• All HTML elements have the box-sizing property set to
border-box.
• This makes sure that the padding and border are included
in the total width and height of the elements.
*{
box-sizing: border-box;
}

.menu {
width: 25%;
float: left;
}
.main {
width: 75%;
float: left;
}

CSE3150 – Front-end Full Stack


16
Development
Building a Responsive Grid-View -
Example

Refer Pgm2

CSE3150 – Front-end Full Stack


17
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


18
Development
Media Queries
• Media query is a CSS technique introduced in CSS3.
• It uses the @media rule to include a block of CSS properties
only if a certain condition is true.
• E.g.: If the browser window is 600px or smaller, the
background color will be lightblue
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}

CSE3150 – Front-end Full Stack


19
Development
Media Queries
• Use a media query to add a breakpoint at 768px:
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
@media only screen and (max-width: 768px) {
/* For mobile phones: */
[class*="col-"] {
width: 100%;
} }

CSE3150 – Front-end Full Stack


20
Development
Typical Device Breakpoints
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {...}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}

/* Medium devices (landscape tablets, 768px and up) */


@media only screen and (min-width: 768px) {...}

/* Large devices (laptops/desktops, 992px and up) */


@media only screen and (min-width: 992px) {...}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}

CSE3150 – Front-end Full Stack


21
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


22
Development
Images –
Using the width & max-width Property
• If the width property is set to a percentage and the height
property is set to "auto", the image will be responsive and scale up
and down
img {
width: 100%;
height: auto;
}
• If the max-width property is set to 100%, the image will scale
down if it has to, but never scale up to be larger than its original
size
img {
max-width: 100%;
height: auto;
}

CSE3150 – Front-end Full Stack


23
Development
Images -
Background Images
• Background images can also respond to resizing & scaling.
• 3 different methods
1. If the background-size property is set to "contain", the
background image will scale, and try to fit the content
area. However, the image will keep its aspect ratio (the
proportional relationship between the image's width and
height)
2. If the background-size property is set to "100% 100%",
the background image will stretch to cover the entire
content area.
3. If the background-size property is set to "cover", the
background image will scale to cover the entire content
area. Here, the "cover" value keeps the aspect ratio, and
some part of the background image may be clipped.

CSE3150 – Front-end Full Stack


24
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


25
Development
Videos - Add a Video
• When we want to add a video in our web page, the video will
be resized to always take up all the available space

CSE3150 – Front-end Full Stack


26
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


27
Development
Frameworks
• There are many free CSS Frameworks that offer Responsive
Design.
• A popular framework is Bootstrap. It uses HTML and CSS to
make responsive web pages.
• Other Frameworks
– Tailwind CSS
– Bulma
– Materialize
– Foundation by Zurb
– Pure CSS
– Element
– Skeleton
– Metro UI
– Powertocss

CSE3150 – Front-end Full Stack


28
Development
Frameworks – Bootstrap – Example

Refer Pgm3

CSE3150 – Front-end Full Stack


29
Development
Responsive Web Design

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


30
Development
Templates

• There are some responsive templates available with the CSS


framework.
• You are free to modify, save, share, and use them in all your
projects.
• E.g.:
– Ecommerce
– Education
– Restaurant
– Art Template
– Architect Template
– Blog Template
– CV Template

CSE3150 – Front-end Full Stack


31
Development
Responsive Web Design (Completed)

• Introduction
• Viewport
• Grid View
• Media Queries
• Images
• Videos
• Frameworks
• Templates

CSE3150 – Front-end Full Stack


32
Development
Bootstrap
• Introduction
• Create Your First Web Page With Bootstrap 5
• Containers
• Grid System
• Colors
• Tables
• Images
• Buttons
• Elements
• Forms
• Select menu
• Validation
• Components

CSE3150 – Front-end Full Stack


33
Development
Bootstrap
• Bootstrap 5 is the newest version of Bootstrap, which is the
most popular HTML, CSS, and JavaScript framework for
creating responsive, mobile-first websites.
• Bootstrap is a free and open-source CSS framework directed
at responsive, mobile-first front-end web development.
• It contains HTML, CSS and JavaScript-based design
templates for typography, forms, buttons, navigation, &
other interface components.
• Bootstrap is a free front-end framework for faster and easier
web development

CSE3150 – Front-end Full Stack


34
Development
Bootstrap
• Bootstrap was developed by Mark Otto and Jacob
Thornton at Twitter, and released as an open source
product in August 2011 on GitHub.
• It contains pre-built components and design elements to
style HTML content.
• Modern browsers such as Chrome, Firefox, Opera, Safari, &
Internet Explorer support Bootstrap.
• How to Use :
– Download Bootstrap from getbootstrap.com
– Include Bootstrap from a CDN

CSE3150 – Front-end Full Stack


35
Development
Bootstrap
• Download Bootstrap from getbootstrap.com
– If you want to download and host Bootstrap yourself, go
to getbootstrap.com, and follow the instructions there.
• Include Bootstrap from a CDN
– If you don't want to download and host Bootstrap
yourself, you can include it from a CDN (Content Delivery
Network).
– MaxCDN provides CDN support for Bootstrap's CSS and
JavaScript. You must also include jQuery.

CSE3150 – Front-end Full Stack


36
Development
Bootstrap CDN
• You must include the following Bootstrap’s CSS, JavaScript, and
jQuery from MaxCDN into your web page.

<!-- Latest compiled and minified Bootstrap CSS -->


<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bo
otstrap/3.3.7/css/bootstrap.min.css">

<!-- Latest compiled Bootstrap JavaScript -->


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/
js/bootstrap.min.js"></script>

<!-- latest jQuery library -->


<script src="https://code.jquery.com/jquerylatest.js"></script>

CSE3150 – Front-end Full Stack


37
Development
Advantages of Bootstrap

• Easy to use: Anybody with just basic knowledge of HTML


and CSS can start using Bootstrap
• Responsive features: Bootstrap's responsive CSS adjusts to
phones, tablets, and desktops
• Mobile-first approach: In Bootstrap 3, mobile-first styles
are part of the core framework
• Browser compatibility: Bootstrap is compatible with all
modern browsers (Chrome, Firefox, Internet Explorer,
Safari, and Opera)

CSE3150 – Front-end Full Stack


38
Development
Advantage of using the Bootstrap CDN

• Many users already have downloaded Bootstrap from


MaxCDN when visiting another site. As a result, it will be
loaded from cache when they visit your site, which leads to
faster loading time.
• Also, most CDN's will make sure that once a user requests a
file from it, it will be served from the server closest to them,
which also leads to faster loading time.

CSE3150 – Front-end Full Stack


39
Development
Create Your First Web Page With Bootstrap 5

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

CSE3150 – Front-end Full Stack


40
Development
Bootstrap 5 is mobile-first

• Bootstrap 5 is designed to be responsive to mobile devices.


• Mobile-first styles are part of the core framework.
• To ensure proper rendering and touch zooming, add the
following <meta> tag inside the <head> element.
<meta name="viewport" content="width=device-width, initial-scale=1">

– The width=device-width part sets the width of the page to follow


the screen-width of the device (which will vary depending on the
device).

– The initial-scale=1 part sets the initial zoom level when the page
is first loaded by the browser.

CSE3150 – Front-end Full Stack


41
Development
Containers

• Bootstrap 5 also requires a containing element to wrap site


contents.
• There are 2 container classes to choose from:
1. The .container class provides a responsive fixed width
container
2. The .container-fluid class provides a full width
container, spanning the entire width of the viewport

CSE3150 – Front-end Full Stack


42
Development
Containers

• Bootstrap 5 also requires a containing element to wrap site


contents.
• There are 2 container classes to choose from:
1. The .container class provides a responsive fixed width
container
2. The .container-fluid class provides a full width
container, spanning the entire width of the viewport

CSE3150 – Front-end Full Stack


43
Development
Grid System

• Bootstrap's grid system is built with flexbox and allows up to


12 columns across the page.
• If you do not want to use all 12 columns individually, you can
group the columns together to create wider columns

CSE3150 – Front-end Full Stack


44
Development
Grid Classes

• The Bootstrap 5 grid system has six classes:


• .col- (extra small devices - screen width less than 576px)
• .col-sm- (small devices - screen width equal to or greater
than 576px)
• .col-md- (medium devices - screen width equal to or
greater than 768px)
• .col-lg- (large devices - screen width equal to or greater
than 992px)
• .col-xl- (xlarge devices - screen width equal to or greater
than 1200px)
• .col-xxl- (xxlarge devices - screen width equal to or greater
than 1400px)

CSE3150 – Front-end Full Stack


45
Development
Colors

• Bootstrap 5 has some contextual classes that can be used


to provide "meaning through colors".
• The classes for text colors are:
.text-muted, .text-primary, .text-success, .text-info,
.text-warning, .text-danger, .text-secondary, .text-white,
.text-dark, .text-body (default body color/often black)
and .text-light

CSE3150 – Front-end Full Stack


46
Development
Colors – Example

Refer Pgm4

CSE3150 – Front-end Full Stack


47
Development
Tables
• A basic Bootstrap 5 table has a light padding and horizontal
dividers.
– The .table class adds basic styling to a table
– The .table-striped class adds zebra-stripes to a table
– The .table-bordered class adds borders on all sides of the table and
cells
– The .table-hover class adds a hover effect (grey background color) on
table rows
– The .table-dark class adds a black background to the table
– Combine .table-dark and .table-striped to create a dark, striped
table
– The .table-borderless class removes borders from the table
– The .table-sm class makes the table smaller by cutting cell padding
in half
– The .table-responsive class adds a scrollbar to the table when
needed (when it is too big horizontally)

CSE3150 – Front-end Full Stack


48
Development
Images
• Rounded Corners
– The .img-rounded class adds rounded corners to an image
(IE8 does not support rounded corners)
• Circle
– The .img-circle class shapes the image to a circle (IE8 does
not support rounded corners)
• Thumbnail
– The .img-thumbnail class shapes the image to a thumbnail

CSE3150 – Front-end Full Stack


49
Development
Images
• Responsive Images
– Images comes in all sizes. So do screens. Responsive images
automatically adjust to fit the size of the screen.
– Create responsive images by adding an .img-responsive class
to the <img> tag. The image will then scale nicely to the parent
element.
– The .img-responsive class applies display: block; and max-
width: 100%; and height: auto; to the image

CSE3150 – Front-end Full Stack


50
Development
Buttons
• Bootstrap provides seven styles of buttons with the following
classes:
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link
• Refer Pgm5

CSE3150 – Front-end Full Stack


51
Development
Button Sizes
• Bootstrap provides 4 button sizes with the following classes:
.btn-lg
.btn-md
.btn-sm
.btn-xs

CSE3150 – Front-end Full Stack


52
Development
Elements
• The button classes can be used on the following elements:
– <a>
– <button>
– <input>

CSE3150 – Front-end Full Stack


53
Development
Forms – Stacked Form
• All textual <input> and <textarea> elements with class
.form-control get proper form styling

• Refer Pgm6

CSE3150 – Front-end Full Stack


54
Development
Select - Select Menu
• Select menu (select one)
• Multiple select menu (hold ctrl or shift (or drag with the
mouse) to select more than one)

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

CSE3150 – Front-end Full Stack


55
Development
Select - Select Menu
• Select menu (select one)
• Multiple select menu (hold ctrl or shift (or drag with the
mouse) to select more than one)

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

CSE3150 – Front-end Full Stack


56
Development
Select - Select Menu – Example
• Refer Pgm7

CSE3150 – Front-end Full Stack


57
Development
Validation - Form Validation
• You can use different validation classes to provide valuable
feedback to users.
• Add either .was-validated or .needs-validation to the <form>
element, depending on whether you want to provide validation
feedback before or after submitting the form.
• The input fields will have a green (valid) or red (invalid) border to
indicate what's missing in the form.
• You can also add a .valid-feedback or .invalid-feedback
message to tell the user explicitly what's missing, or needs to be
done before submitting the form.

CSE3150 – Front-end Full Stack


58
Development
Validation - Form Validation
• Refer Pgm8

CSE3150 – Front-end Full Stack


59
Development
Components (Self study topics)
• Accordion • Modal
• Alerts • Navs & tabs
• Badge • Navbar
• Breadcrumb • Offcanvas
• Buttons • Pagination
• Button group • Popovers
• Card • Progress
• Carousel • Scrollspy
• Close button • Spinners
• Collapse • Toasts
• Dropdowns • Tooltips
• List group

CSE3150 – Front-end Full Stack


60
Development
Bootstrap (Completed)
• Introduction
• Create Your First Web Page With Bootstrap 5
• Containers
• Grid System
• Colors
• Tables
• Images
• Buttons
• Elements
• Forms
• Select menu
• Validation
• Components

CSE3150 – Front-end Full Stack


61
Development
Module 2 - Syllabus

[Lecture-5 Hrs, Practical-6 Hrs, Application]


BootStrap for Responsive Web Design; (Completed)

JavaScript – Core syntax, HTML DOM, objects, classes, Async;

Ajax and jQuery Introduction.

CSE3150 – Front-end Full Stack


62
Development
CSE3150 – Front-end Full Stack
63
Development
What is Ajax?
An Asynchronous JavaScript and XML
Technique for creating fast and dynamic web pages
It allows web pages to be updated asynchronously by exchanging
small amounts of data with the server behind the scenes
This means that it is possible to update parts of a web page without
reloading the whole page
Classic web pages, (which do not use AJAX) must reload the entire
page if the content should change
Examples of applications using AJAX: Google Maps, Gmail, YouTube,
and Facebook
Advantages of AJAX

Reduce server traffic and increase speed


• The first and foremost advantage of Ajax is its ability to improve the
performance and usability of web applications.
• To explain more detailedly, Ajax techniques allow applications to
render without data, which reduces the server traffic inside requests.
That being said, web developers can lower the time consumption on
both side’s responses significantly.
• As a result, your web’s visitors will never have to see a white window
and wait for pages to refresh with Ajax implementation.
• Enable asynchronous calls
• Ajax benefits web developers in how its framework can be used for lazy
loading. Those who don’t know what Lazy Loading is are an optimization
technique that’s widely used for online content.
• In essence, Ajax allows its users to make asynchronous calls to the web
server without reloading the whole web page. As a web visitor, you don’t
have to wait for the entire page to load entirely in order to access the
entire page content.
• The concept of lazy loading assists in loading only the required section and
delays the remaining, until it is needed by users. Thus, Ajax Lazy Loading
not only improves a web page load it also has a positive impact on user
experience and conversion rates.
• XMLHttpRequest
• XMLHttpRequest is a request type widely used for sending a request
to Ajax pages. You can also call it with a different name: Asynchronous
HTTP request. It plays a vital role in the implementation of Ajax
techniques for web development.
• XMLHttpRequest transfers and manipulates the XML data to and from
a web service using HTTP. Its purpose is to establish an independent
connection between the webpage’s client-side and server.
• Reduce bandwidth usage
• One more advantage of Ajax comes from the bandwidth usage. This
action is effective in improving web performance and load speed as
well.
• Ajax makes the best use of the server’s bandwidth by fetching particle
contents instead of transmitting the entire page’s content. This means
that you can bring data from the database and store it into the
database to perform background without reloading the page.
• Form Validation
• In contrast to traditional form submission, where client-side
validations occur after submission, the AJAX method enables precise
and immediate form validation. AJAX provides speed, which is also
one of its significant benefits.
Disadvantages of Ajax

• 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

• synchronous: user must wait while new pages load


• the typical communication pattern used in web pages
(click, wait, refresh)

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

• asynchronous: user can keep interacting with page


while data loads
• communication pattern made possible by Ajax

CS380 13
XMLHttpRequest (and why we won't use it)

• JavaScript includes an XMLHttpRequest object that can fetch files


from a web server
• supported in IE5+, Safari, Firefox, Opera, Chrome, etc. (with minor
compatibilities)
• it can do this asynchronously (in the background, transparent to user)
• the contents of the fetched file can be put into current web page
using the DOM

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

• construct a Prototype Ajax.Request object to request


a page from a server using Ajax
• constructor accepts 2 parameters:
1. the URL to 1. fetch, as a String,
2. a set of options, as an array of key : value pairs in {}
braces (an anonymous JS object)
18
Prototype Ajax methods and properties
option description
how to fetch the request from
method
the server (default "post")
query parameters to pass to
parameters
the server, if any
asynchronous (default true), contentType, encoding,
requestHeaders

options that can be passed to the Ajax.Request constructor

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.

events in the Ajax.Request object that you can handle

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

• cannot be run from a web page stored on your hard drive


• can only be run on a web page stored on a web server
• can only fetch files from the same site that the page is on
www.foo.com/a/b/c.html can only fetch from www.foo.com

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

• Ajax.Updater fetches a file and injects its content into


an element as innerHTML
• additional (1st) parameter specifies the id of element
to inject into

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.

You might also like