0% found this document useful (0 votes)
37 views139 pages

CS202 Final Term Handouts.....

The document covers various JavaScript concepts, including arrays, methods, comparisons, conditions, loops, and data types. It explains the use of arrays versus objects, common array methods, comparison and logical operators, and different types of loops such as for, while, and do/while. Additionally, it discusses break and continue statements, data types, and type conversion in JavaScript.

Uploaded by

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

CS202 Final Term Handouts.....

The document covers various JavaScript concepts, including arrays, methods, comparisons, conditions, loops, and data types. It explains the use of arrays versus objects, common array methods, comparison and logical operators, and different types of loops such as for, while, and do/while. Additionally, it discusses break and continue statements, data types, and type conversion in JavaScript.

Uploaded by

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

CS202 Final Term Handouts

Lesson# 74 – JavaScript Arrays


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Arrays

Associative arrays
Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays
with named indexes.

What is the Difference between Arrays and Objects?


In JavaScript:

 Arrays use numbered indexes.


 Objects use named indexes.

When to Use Arrays? When to use Objects?


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

Avoid new Array()


There is no need to use the JavaScript's built-in array constructor new Array(). Use [] instead. The new
keyword complicates your code and produces nasty side effects.

Lesson# 75 – Array Methods


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Array methods


valueOf() method
The valueOf() method is the default behavior for an array. It returns an array as a string.

pop() method
The pop() method removes the last element from an array. The pop() method returns the value that was
"popped out".

push() method
The push() method adds a new element to an array (at the end).

shift() method
The shift() method removes the first element of an array, and "shifts" all other elements one place up.
The shift() method returns the value that was "shifted out".

Delete elements
Elements can be deleted by using the JavaScript operator delete.

splice() method
The splice() method can be used to add new items to an array.

sort() method
The sort() method sorts an array alphabetically.

reverse() method
The reverse() method reverses the elements in an array.

Lesson# 76 – JavaScript Array Methods


Learning objectives

After completing this topic, a student will be able to:


 Use JavaScript Array Methods

concat() method
The concat() method creates a new array by concatenating two arrays.

slice() method
The slice() method slices out a piece of an array into a new array

Lesson# 77 – JavaScript Comparisons


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Comparison Operators


 Use JavaScript Logical Operators
 Use JavaScript Conditional (Ternary) Operator
 Use JavaScript Bitwise Operators

JavaScript Comparisons
Comparison and Logical operators are used to test for true or false. Comparison operators are
used in logical statements to determine equality or difference between variables or values.
Logical operators are used to determine the logic between variables or values. JavaScript also
contains a conditional operator that assigns a value to a variable based on some condition.

JavaScript also has Bitwise Operators. Bit operators work on 32-bit numbers. Any numeric
operand in the operation is converted into a 32-bit binary number. The result is converted back
to a JavaScript number.

Comparison Operators
Operator Description
== equal to

=== equal value and equal type


!= not equal
!== not equal value or not equal type

> greater than


< less than
>= greater than or equal to
<= less than or equal to

Logical Operators
Operator Description
&& and
|| or
! not

Conditional (Ternary) Operator


JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.

Syntax

variablename = (condition) ? value1:value2

Example

var voteable = (age < 18) ? "Too young":"Old enough";

If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise
the value of voteable will be "Old enough".

JavaScript Bitwise Operators


Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is
1
~ NOT Inverts all the bits
<< Zero fill left shift Shifts left by pushing zeros in from the
right and let the leftmost bits fall off
>> Signed right shift Shifts right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the
left, and let the rightmost bits fall off

Lesson# 78 – JavaScript Conditions


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Conditions

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if: Use if to specify a block of code to be executed, if a specified condition is true


 else: Use else to specify a block of code to be executed, if the same condition is false
 else if : Use else if to specify a new condition to test, if the first condition is false
 switch: Use switch to specify many alternative blocks of code to be executed

Flow Chart of if-else


The following flow chart shows how the if-else statement works.

Example
Code Out Put
<!DOCTYPE html>

<html>
<body>

<h2>JavaScript if .. else</h2>

<p id="demo"></p>

<script>

var a = 30, b = 20,result;

if (a > b) {

result='a is greater than b';

} else if (a < b) {

result='a is less than b';

} else {

result='a is equal to b';

document.getElementById("demo").innerHTML =
result;

</script>

</body>

</html>

Lesson# 79 – JavaScript Switch Statement


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Switch Statement

Switch Statement
You can use multiple if...else…if statements, to perform a multi way branch. However, this is
not always the best solution, especially when all of the branches depend on the value of a
single variable.

Instead you can use a switch statement which handles exactly this situation, and it does so
more efficiently than repeated if...else if statements.

Flow Chart

The following flow chart explains a switch-case statement works.

Syntax

switch (expression) {

case condition 1: statement(s)

break;

case condition 2: statement(s)

break;

...

case condition n: statement(s)

break;

default: statement(s)

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
Example
Code Out Put
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Switch</h2>

<p id="demo"></p>

<script>

var flower = "rose", result;

switch (flower){

case "rose":

result="Roses are red";

break;

case "violet":

result="Violets are blue";

break;

case "sunflower":

result="Sunflowers are yellow";

break;

default:

result="Please select another flower";

document.getElementById("demo").innerHTML =
result;
</script>

</body>

</html>

Lesson# 80 – JavaScript For Loop


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript For Loop

What are loops?


Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions
typically return true or false when analyzed. A loop will continue running until the defined
condition returns false.

Different Kinds of Loops

Here are different kinds of loops used in this language:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

The for loop


The 'for' loop is the most compact form of looping. It includes the following three important
parts −

 The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true, then
the code given inside the loop will be executed, otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.
Flow Chart

The flow chart of a for loop in JavaScript would be as follows −

Syntax

The syntax of for loop in JavaScript is as follows −

for (initialization; test condition; iteration statement) {


Statement(s) to be executed if test condition is true
}

For loop example


Code Out Put
<html>

<body>

<p id="demo"></p>

<script type = "text/javascript">

var count;

document.getElementById("demo").innerHTML+="Starting
Loop" + "<br />";

for(count = 0; count < 10; count++) {

document.getElementById("demo").innerHTML+="Current Count :
" + count+"<br>";

document.write("<br />");

document.getElementById("demo").innerHTML+="Loop
stopped!";

</script>

</body>

</html>

Lesson# 81 – JavaScript While Loop


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript While Loop


 Use JavaScript Do/While Loop

Loop statements
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce
the number of lines.

JavaScript supports all the necessary loops to ease down the pressure of programming.

The while Loop


The most basic loop in JavaScript is the while loop. The purpose of a while loop is to execute a
statement or code block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.

Flow Chart

The flow chart of while loop looks as follows −

Syntax

The syntax of while loop in JavaScript is as follows −

while (expression) {
Statement(s) to be executed if expression is true
}

While Loop Example


Code Out Put
<html>

<body>

<p id="demo"></p>

<script>

var myBankBalance = 0;

var msg = "";

while (myBankBalance <= 10) {

msg = msg + "My bank balance is $" +


myBankBalance + "<br>";

myBankBalance ++;

document.getElementById("demo").innerHTML=msg;

</script>

</body>

</html>

Do/While Loop Example


Code Out Put
<!DOCTYPE HTML>

<html>

<body>
<h3>JavaScript do-while Loop Example</h3>

<p id="demo"></p>

<script type="text/javascript">

var num = 3;

document.getElementById("demo").innerHTML+=

"Printing the table of " + num + "<br/>";

var i = 1;

do

document.getElementById("demo").innerHTML+=

num*i + "<br/>";

i++;

} while(i<=10);

document.getElementById("demo").innerHTML+="Done!";

</script>

</body>

</html>

Lesson# 82 – JavaScript Break and Continue


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Break and Continue statements

JavaScript break and continue statements


JavaScript provides full control to handle loops and switch statements. There may be a situation
when you need to come out of a loop without reaching its bottom. There may also be a
situation when you want to skip a part of your code block and start the next iteration of the
loop.

To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.

The break Statement


The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.

Flow Chart

The flow chart of a break statement would look as follows −

The Continue Statement


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

Break Statement example code


The following example illustrates the use of a break statement with a while loop. Notice how the loop
breaks out early once x reaches 5.

Code Out Put


<html>

<body>

<p id="demo"></p>

<script type = "text/javascript">

<!--

var x = 1;
document.getElementById("demo").innerHTML+="Entering the
loop<br /> ";

while (x < 20) {

if (x == 5) {

break; // breaks out of loop completely

x = x + 1;

document.getElementById("demo").innerHTML+= x +
"<br />";

document.getElementById("demo").innerHTML+="Exiting
the loop!<br /> ";

//-->

</script>

</body>

</html>

The continue Statement example


This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5.

code Out Put


<html>

<body>
<p id="demo"></p>

<script type = "text/javascript">

<!--

var x = 1;

var msg="";

msg+="Entering the loop<br /> ";

while (x < 10) {

x = x + 1;

if (x == 5) {

continue; // skip rest of the loop body

msg+= x + "<br />";

msg+="Exiting the loop!<br /> ";

document.getElementById("demo").innerHTML=msg;

//-->

</script>

</body>
</html>

Lesson# 83 – JavaScript Data Type


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Data Types

Data Types in JavaScript


Data types basically specify what kind of data can be stored and manipulated within a program.

In JavaScript there are 5 different data types that can contain values:

 String
 Number
 Boolean
 Object
 Function

There are 3 types of objects:

 Object
 Date
 Array

And 2 data types that cannot contain values:

 null
 undefined

typeof operator
You can use the typeof operator to find the data type of a JavaScript variable.

Constructor
A constructor is a function that creates an instance of a class which is typically called an “object”. In
JavaScript, a constructor gets called when you declare an object using the new keyword. The purpose of
a constructor is to create an object and set values if there are any object properties present.
Constructor Property
The constructor property returns the constructor function for all JavaScript variables.

Lesson# 84 – JavaScript Type Conversion


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Type Conversion functions

What is type conversion?


In programming, type conversion is the process of converting data of one type to another. For
example: converting String data to Number.

JavaScript Type Conversion


JavaScript variables can be converted to a new variable and another data type:

 By the use of a JavaScript function


 Automatically by JavaScript itself

global method String()


 The global method String() can convert numbers to strings. It can be used on any type of
numbers, literals, variables, or expressions. The Number method toString() does the
same.
 The global method String() can convert booleans to strings.
 The global method String() can convert dates to strings.

global method Number()


 The global method Number() can convert strings to numbers. Strings containing
numbers (like "3.14") convert to numbers (like 3.14). Empty strings convert to 0.
 The global method Number() can also convert booleans to numbers.
 The global method Number() can be used to convert dates to numbers.

The Unary + Operator


The unary + operator can be used to convert a variable to a number. If the variable cannot be converted,
it will still become a number, but with the value NaN (Not a number).

Automatic String Conversion


JavaScript automatically calls the variable's toString() function when you try to "output" an object or a
variable.

JavaScript Type Conversion Table


The table below shows the result of converting different JavaScript values to Number, String, and
Boolean:

Original Converted Converted Converted


Value to Number to String to Boolean
false 0 "false" false
true 1 "true" true
0 0 "0" false
1 1 "1" true
"0" 0 "0" true
"1" 1 "1" true
NaN NaN "NaN" false
Infinity Infinity "Infinity" true
-Infinity -Infinity "-Infinity" true
"" 0 "" false
"20" 20 "20" true
"twenty" NaN "twenty" true
[] 0 "" true
[20] 20 "20" true
[10,20] NaN "10,20" true
["twenty"] NaN "twenty" true
["ten","twenty"] NaN "ten,twenty" true
function(){} NaN "function(){}" true
{} NaN "[object Object]" true
null 0 "null" false
undefined NaN "undefined" false

Lesson# 85 – JavaScript Regular Expressions


Learning objectives

After completing this topic, a student will be able to:


 Use different methods of JavaScript Regular Expressions

What is regular expression?


A regular expression is a sequence of characters that forms a search pattern. The search pattern

can be used for text search and texts replace operations. When you search for data in a text, you

can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern. Regular

expressions can be used to perform all types of text search and texts replace operations.

Syntax

/pattern/modifiers;

Example:

var patt = /text/i

Using String search() and replace() With String


The search() method searches a string for a specified value and returns the position of the match.

Example

Code Out Put


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>Search a string for "university", and display the


position of the match:</p>

<p id="demo"></p>

<script>
var text = "Virtual University!";

var n = text.search(/university/i);

document.getElementById("demo").innerHTML = n;

</script>

</body>

</html>

The replace() method replaces a specified value with another value in a string.

Example

Code Out Put


<!DOCTYPE html>
On click of button string will be replaced
<html>

<body>

<h2>JavaScript String Methods</h2>

<p>Replace "Canada" with "Pakistan" in the


paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Canada!</p>

<script>

function myFunction() {

var text =
document.getElementById("demo").innerHTML;

document.getElementById("demo").innerHTML
=

text.replace(/canada/i, "Pakistan");
}

</script>

test() and exec() methods


The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or
false, depending on the result.

Example

Code Out Put


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p>Search for a "v" in the next paragraph:</p>

<p id="p01">Virtual University!</p>

<p id="demo"></p>

<script>

var text =
document.getElementById("p01").innerHTML;

var pattern = /v/;

document.getElementById("demo").innerHTML
= pattern.test(text);

</script>

</body>
</html>

The exec() method is a RegExp expression method. It searches a string for a specified pattern, and
returns the found text as an object. If no match is found, it returns an empty (null) object.

Code Out Put


<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Regular Expressions</h2>

<p id="demo"></p>

<script>

var obj = /e/.exec("Virtual University!");

document.getElementById("demo").innerHTML =

"Found " + obj[0] + " in position " + obj.index + " in


the text: " + obj.input;

</script>

</body>

</html>

Lesson# 86 – JavaScript Hoisting


Learning objectives

After completing this topic, a student will be able to:

 Define JavaScript Hoisting

Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the
top of their scope before code execution. This means that no matter where functions and
variables are declared, they are moved to the top of their scope regardless of whether their
scope is global or local. however, is the fact that the hoisting mechanism only moves the
declaration. The assignments are left in place.

JavaScript Declarations are Hoisted


In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used
before it has been declared.

JavaScript Initializations are Not Hoisted


JavaScript only hoists declarations, not initializations.

Declare Your Variables At the Top !


Hoisting is an unknown or overlooked behavior of JavaScript. If a developer doesn't understand hoisting,
programs may contain bugs (errors). To avoid bugs, always declare all variables at the beginning of every
scope.

Lesson# 87 – JavaScript Error Handling


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Error Handling

Types of Errors
There are three types of errors in programming:

a. Syntax Errors
b. Runtime Errors
c. Logical Errors

Syntax Errors

Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.

For example, the following line causes a syntax error because it is missing a closing parenthesis.

<script type = "text/javascript">


<!--

window.print(;

//-->

</script>

When a syntax error occurs in JavaScript, only the code contained within the same thread as
the syntax error is affected and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.

Runtime Errors

Runtime errors, also called exceptions, occur during execution (after


compilation/interpretation).

For example, the following line causes a runtime error because here the syntax is correct, but at
runtime, it is trying to call a method that does not exist.

<script type = "text/javascript">

<!--

window.printme();

//-->

</script>

Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.

Logical Errors

Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.

You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.

JavaScript Error Handling


 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and catch, regardless of the result.

Example

Code Out Put


<!DOCTYPE html>
Entering value greater than 10
<html>

<body>

<h2>JavaScript try catch</h2>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">

<button type="button" onclick="myFunction()">Test


Input</button>

<p id="p01"></p>

<script>

function myFunction() {

const message = document.getElementById("p01");

message.innerHTML = "";

let x = document.getElementById("demo").value;

try {

if(x == "") throw "Input field is empty";

if(isNaN(x)) throw "Enter number only";

x = Number(x);

if(x > 10) throw "Value must be lesser than 10";


if(x < 5) throw "Value must be greater than 5";

catch(err) {

message.innerHTML = "Error : " + err;

finally {

Lesson# 88 – JavaScript Debugging


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Debugging tools

Code Debugging
Programming code might contain syntax errors, or logical errors. Many of these errors are difficult
to diagnose.

Often, when programming code contains errors, nothing will happen. There are no error messages,
and you will get no indications where to search for errors.

Searching for (and fixing) errors in programming code is called code debugging.

JavaScript Debuggers
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.

Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

With a debugger, you can also set breakpoints (places where code execution can be stopped), and
examine variables while the code is executing.

The console.log() Method Example


Code
<!DOCTYPE html>

<html>

<body>

<h1>My First Web Page</h1>

<script>

a = 15;

b = 6;

c = a * b;

console.log("The value of C is : "+c);

</script>

</body>

</html>
Out Put in Google Chrome

Lesson# 89 – JavaScript Best Practices


Learning objectives

After completing this topic, a student will be able to:

 Explain and implement JavaScript Best Practices

JavaScript Best Practices


 Minimize the use of global variables.
 All variables used in a function should be declared as local variables. Local variables must be
declared with the var keyword, otherwise they will become global variables.
 It is a good coding practice to put all declarations at the top of each script or function.
 It is a good coding practice to initialize variables when you declare them.
 Always treat numbers, strings, or Booleans as primitive values. Not as objects. Declaring these
types as objects, slows down execution speed, and produces nasty side effects.
 Don't Use new Object().
 Beware of Automatic Type Conversions.

Lesson# 90 – JavaScript Best Practices


Learning objectives

After completing this topic, a student will be able to:

 Explain and implement JavaScript Best Practices

JavaScript Best Practices


 Use === Comparison. The === operator forces comparison of values and type.
 Use Parameter Defaults. If a function is called with a missing argument, the value of the missing
argument is set to undefined. Undefined values can break your code. It is a good habit to assign
default values to arguments.
 End Your Switches with Defaults. Even if you think it’s not needed.
 Avoid Using eval(), because it allows arbitrary code to be run, it also represents a security
problem.

Lesson# 91 – JavaScript Common Mistakes


Learning objectives

After completing this topic, a student will be able to:

 Identify and explain JavaScript Common Mistakes

JavaScript Common Mistakes


Accidentally Using the Assignment Operator

JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment
operator (=), instead of a comparison operator (==) in an if statement.

Expecting Loose Comparison


It is a common mistake to forget that switch statements use strict comparison.

Confusing Addition & Concatenation

Addition is about adding numbers. Concatenation is about adding strings. In JavaScript both operations
use the same + operator. Because of this, adding a number as a number will produce a different result
from adding a number as a string.

Misunderstanding Floats

All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming
languages, including JavaScript, have difficulties with precise floating point values.

Example

var x = 0.1;
var y = 0.2;
var z = x + y // the result in z will not be 0.3

To solve the problem above, it helps to multiply and divide,

var z = (x * 10 + y * 10) / 10; // x will be 0.3

Breaking a JavaScript String

JavaScript will allow you to break a statement into two lines. But, breaking a statement in the middle of
a string will not work. You must use a "backslash" if you must break a statement in a string.

Misplacing Semicolon

Because of a misplaced semicolon, this code block will execute regardless of the value of x:

Code Out Put


<!DOCTYPE html>

<html>

<body>

<h2>Common JavaScript Mistakes</h2>

<p id="demo"></p>

<script>
var x = 5;

if (x == 19);

document.getElementById("demo").innerHTML =
"Hello";

</script>

</body>

</html>

Breaking a Return Statement

Example

function myFunction(a) {
var power = 10;
return
a * power;
}

The function will return undefined!

Accessing Arrays with Named Indexes

If you use a named index, when accessing an array, JavaScript will redefine the array to a standard
object. After the automatic redefinition, array methods and properties will produce undefined or
incorrect results.

Lesson# 92 – JavaScript Common Mistakes


Learning objectives

After completing this topic, a student will be able to:

 Identify and explain JavaScript Common Mistakes

What is JSON?
JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting
data. JSON is often used when data is sent from a server to a web page.

JavaScript Common Mistakes


Ending an Array Definition with a Comma

Incorrect:

points = [40, 100, 1, 5, 25, 10,];

Some JSON and JavaScript engines will fail, or behave unexpectedly.

Ending an Object Definition with a Comma

Incorrect:

person = {firstName:"John", lastName:"Doe", age:46,}

Some JSON and JavaScript engines will fail, or behave unexpectedly

Undefined is Not Null

With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an
object has to be defined, otherwise it will be undefined.

Expecting Block Level Scope

JavaScript does not create a new scope for each code block. It is true in many programming languages,
but not true in JavaScript.

Lesson# 93 – JavaScript Performance


Learning objectives

After completing this topic, a student will be able to:

 Improve JavaScript Performance

How to improve JavaScript Performance?


Reduce Activity in Loops

Each statement in a loop, including the for statement, is executed for each iteration of the loop. Search
for statements or assignments that can be placed outside the loop.
Reduce DOM Access

Accessing the HTML DOM is very slow, compared to other JavaScript statements. If you expect to access
a DOM element several times, access it once, and use it as a local variable.

Reduce DOM Size

Keep the number of elements in the HTML DOM small. This will always improve page loading, and speed
up rendering (page display), especially on smaller devices.

Avoid Unnecessary Variables

Don't create new variables if you don't plan to save values.

Delay JavaScript Loading

Putting your scripts at the bottom of the page body, lets the browser load the page first.

Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes.

Lesson# 94 – JavaScript Reserve Words


Learning objectives

After completing this topic, a student will be able to:

 Identify and use JavaScript Reserve Words

JavaScript Reserve Words


There are reserved words that have special meaning in JavaScript and cannot be used in your code as
variables, function names or loop labels.

abstract arguments await* boolean


break byte case catch
char class* const continue
debugger default delete do
double else enum* eval
export* extends* false final
finally float for function
goto if implements import*
in instanceof int interface
let* long native new
null package private protected
public return short static
super* switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield

Words marked with* are new in ECMAScript 5 and 6.

Java Reserved Words


JavaScript is often used together with Java. You should avoid using some Java objects and properties as
JavaScript identifiers:

getClass java JavaArray javaClass


JavaObject JavaPackage

Other Reserved Words


JavaScript can be used as the programming language in many applications.

You should also avoid using the name of HTML and Window objects and properties:

alert all anchor anchors


area assign blur button
checkbox clearInterval clearTimeout clientInformation
close closed confirm constructor
crypto decodeURI decodeURIComponent defaultStatus
document element elements embed
embeds encodeURI encodeURIComponent escape
event fileUpload focus form
forms frame innerHeight innerWidth
layer layers link location
mimeTypes navigate navigator frames
frameRate hidden history image
images offscreenBuffering open opener
option outerHeight outerWidth packages
pageXOffset pageYOffset parent parseFloat
parseInt password pkcs11 plugin
prompt propertyIsEnum radio reset
screenX screenY scroll secure
select self setInterval setTimeout
status submit taint text
textarea top unescape untaint
window

HTML Event Handlers


In addition you should avoid using the name of all HTML event handlers.

Examples:

onblur onclick onerror onfocus


onkeydown onkeypress onkeyup onmouseover
onload onmouseup onmousedown onsubmit

Lesson# 95 – JavaScript Global Functions and Properties


Learning objectives

After completing this topic, a student will be able to:

 Use JavaScript Global Functions and Properties

JavaScript Global Functions and Properties


JavaScript Global Properties
Property Description
Infinity A numeric value that represents positive/negative infinity
NaN "Not-a-Number" value
undefined Indicates that a variable has not been assigned a value
JavaScript Global Functions
Function Description
decodeURI() Decodes a URI
decodeURIComponent() Decodes a URI component
encodeURI() Encodes a URI
encodeURIComponent() Encodes a URI component
escape() Deprecated in version
1.5. Use encodeURI() or encodeURIComponent() instead
eval() Evaluates a string and executes it as if it was script code
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
String() Converts an object's value to a string
unescape() Deprecated in version
1.5. Use decodeURI() or decodeURIComponent() instead

Lesson# 96 – JavaScript Window Object


Learning objectives

 Understand the JS Window Object


 Identify methods of JS Window Object

JavaScript Window Object


The JavaScript Window object represents a window opened in a browser. It is a kind of a container,
which holds the document object, also known as the DOM. Any functions, objects or variables defined
within a window becomes its members. Global functions, objects and variables defined in a document
object are also accessible with the window object.

Multiple iframes (<iframe>) can be defined in a window object. However, one window object is created
for the HTML document while each of the iframes have their own window object.

Window Object Methods


There is a list of methods paired with the window object. Each one of them is used to perform distinct
action required in a window. All these methods can be called using the window object. You will learn a
few methods in this lesson.

setTimeout() and clearTimeout()

As described in the video, setTimeout function sets a timer on a function, so that the function executes
when the time limit set by a timer is reached. See below the pictorial description.

setInterval() and clearInterval()

The setInterval function is the same as the setTimeout function except that it calls the function after
every time interval specified in millseconds as shown in the figure below.
Lesson# 97 - JavaScript and Forms
Learning objectives

 Identify ways to access HTML forms


 Recognize methods for form validation

Accessing JavaScript Forms


You have learnt HTML forms, elements in a form and their attributes. Now, think that you have entered
some data into a form displayed on a webpage and you intend to submit it. What you expect is a
response after submitting or filling out a form, be it a success message or a message showing invalid
format for an email. This is possible by accessing individual elements in a form. You will learn how to
access HTML forms in this topic.

HTML forms used in a webpage can be accessed through JavaScript. One way is to use the method
getElementById. You just need to specify the id of the form in this method.

Another way is to use the document object. By using the document.forms collection, you can retrieve
the collection of all forms in a document. Each <form> element is indexed with its name attribute.

Validation of forms

As you can see forms in an HTML document can be accessed in more than one way, we can utilize these
ways to validate forms. It is up to the developer how he tends to validate components of a form. A form
field can be validated whether it is filled or empty, an email address can be validated for certain
symbols. Similarly, a certain length of a password can be imposed on a user.

There are two ways of form validation, namely:

 Client-side validation
 Server-side validation

Client-side validation is performed using JavaScript. The following lesson video demonstrates examples
of client-side form validations.

HTML Constraints Validation


You have seen how JavaScript can be used to validate forms. HTML utilizes attributes in a form for
validations. As you may have noticed that three ways exist for HTML constraint validation based on:
 HTML Input Attributes
 CSS Pseudo selectors
 DOM properties and methods

Look at the following examples.

1). Use of HTML input attribute: required

2). Use of CSS pseudo selector: invalid

Lesson# 98 – JavaScript Case Study


Learning objectives

 Understand form validation using JavaScript

Form Validation Example


As discussed in previous topic, client-side validation can be performed with JavaScript. In this topic, you
will be examining an example of form validation using JS.

An example has been set out for you in lesson video. A brief description of the code is given below. You
can understand the working of example code in the video.

 A form is created in an HTML document with four fields namely, name, email, city and country.
In order to access the form you need to specify the name attribute of <form> element.
 A callback function is set on “submit” button. On submission of form the function
“validateForm” is invoked.
 validateForm() is a function defined in <script> tag to check whether each one of the fields in the
form are correctly filled or not. If any of given fields fail to validate, a notice is displayed to user.
 showNotice() function embeds a message in the div with the id “notice”. Whereas, clearNotice()
hides any previous displayed notices to user.
 Lastly, there is the function validateEmail(), which validates an email address according to the
specifications of an actual email address.

Lesson# 99 – AJAX Introduction


Learning objectives

 Understanding of AJAX
 Recognize the purpose of using AJAX
 Identify components of AJAX

Introduction to AJAX
Asynchronous JavaScript And XML, also commonly known as AJAX, is a technique used in front-end
development to create dynamic webpages. However, AJAX has its unique features such as:

 It allows you to update a webpage without loading the webpage


 Send data to a web server in the background

Above features make it as a key tool for creating fast dynamic webpages. Google Suggest is one of the
major examples, which utilize AJAX.

Nothing’s new in AJAX

AJAX is not a programming language. In fact, it is a technique based on existing standards used in JS and
XML. AJAX makes use of two key components, which are

 XMLHttpRequest object
 JavaScript DOM

You have familiarized yourself with JavaScript DOM in preceding topics. However, XML HttpRequest
object is a new thing, which will be discussed in upcoming lectures.

Real world examples of AJAX


Google Suggest is one of the examples of usage of AJAX. Similarly, Gmail, Yahoo, Facebook and Google
maps provide users with a dynamic view of webpages without reloading them.

You may have across these applications of AJAX not knowing how it was being done. In next few
lectures, you will be learning more about AJAX.

Lesson# 100 – AJAX Sending Request


Learning objectives

 Learn the steps involved in sending a request to server


 Identify key methods involved in sending XMLHttp request

Sending a request in AJAX


You have been familiarized with the concept of AJAX in previous lesson. AJAX is a technique used in
front-end development to create dynamic webpages. It allows you to update a webpage without loading
the webpage and send data to a web server in the background.

In this lesson, you will understand how a request is initiated in AJAX.

XMLHttpRequest

XMLHttpRequest object is used for communicating with server and updating webpages without
reloading the complete page. All browsers including Chrome, Edge, Firefox and later version of Internet
Explorer have a built-in XMLHttpRequest object. However, older versions of Internet Explorer use
ActiveXObject for creating a XMLHttp request.

XMLHttpRequest object methods

XMLHttpRequest object has a number of methods. Some prominent methods we will be studying are:

 new XMLHttpRequest()
 open()
 send()
 setRequestHeader()

GET vs POST
Now that you have learnt the syntax and use of a few XMLHttpRequest object methods. We shall
proceed further with the methods by which a request is sent that are Get and Post.

The difference between Get and Post can be realized with points given in the following table.

Lesson# 101 – AJAX Sending Request


Learning objectives

 Understanding of open() and send() methods


 Learn to send a simple request to server

Send Request with AJAX


You have learnt in previous lesson that for sending a request with AJAX, you create an XMLHttpRequest
object. There are a number of methods associated with this object. In this lesson open() and send()
methods will be discussed.

open()

First of all, a connection with the server is opened with open(). There are three parameters passed into
this method, which are: the method with which a request is sent, the target file on the server, the
nature of request. The syntax of open() looks something like the one given below:

The value true here represents that the request will be sent asynchronously that is, the webpage will not
be loaded as a whole and a dynamic view of the webpage will be created.

send() and send(string)

Another method send() is used after a connection is opened with the server. This method is used to
send the request to server. There are two variations to this method, send() and send(string). Send() is
used to place a request with method GET or POST and send(string) on the other hand is for sending a
request with POST.

Synchronous and Asynchronous data transfer


As discussed in the video, you can specify the third parameter in open() method as TRUE or FALSE. By
TRUE, you set the request as Asynchronous. On the other hand, if this parameter is set as FALSE, you set
the request as a synchronous request. However, AJAX request can only be asynchronous.

How browsers identify whether a change has


occurred or not?
You have been listening for a few lessons now that with AJAX we send an asynchronous request and the
webpage is not reloaded and even then we get a dynamic view of the same page. How does it really
happen?

There is a property of XMLHttpRequest namely, onreadystatechange. This can help the browsers to
know that some change has occurred in the webpage and a response has been received. When this
change is acknowledged, a function associated with this event is invoked. You can perform necessary
actions required after the response in that function.
Lesson# 102 – AJAX Receiving Response
Learning objectives

 Learn to receive a response in AJAX


 Identify essential properties associated with server response

Receiving response from server


After a request is processed at server end, a suitable response relative to the request is generated and
sent back to the browser. This response is received as simple text or XML. The property with which you
can read the response is responseText or responseXML.

For differentiation, you can say that if the fetched response is in XML format then responseXML is used.
However, if a response is in either text or XML format, responseText is a feasible option.

onreadystatechange

onreadystatechange is an event with which the state of XMLHttpRequest can be identified. Typically, a
pointer to a function is stored, which is invoked when the readystatechange event occurs.

There are two properties usually associated with this event, to know the status of request and expected
response. These are:

 readystate
 status

readystate

This is the property that indicates change in state and resultantly, the function associated with
onreadystatechange event invokes. This property can hold values ranging from 0 to 4. You will study
them further in the video lesson.

status

The status of XMLHttpRequest object is held by status property. The acquired response may or may not
be available when returned to the requesting browser. To check this condition, you can use status
property.

Steps for sending a request and receiving a


response in AJAX
You have gone through some basic steps involved in sending a request and receiving its response. In this
section a brief summary of the steps is listed out for you that is given below:
1. Create an XMLHttpRequest object.
2. Define a pointer to a function that is invoked as a result of onreadystatechange event.
3. In the function, perform necessary checks to ensure that the response has been received and is
accessible. You can check the readyState and status property of your request object.
4. Open a connection to the server with open(), when required actions are stated on reception of
an expected response from server.
5. Lastly, use send method for sending the request.

Lesson# 103 - AJAX Receiving Response


Learning objectives

 Recognize the use of callback functions


 Learn to utilize responseText and responseXML properties to read AJAX responses

Callback functions
A callback function is a function passed as an argument to another function. This callback function is
sent as a parameter, which is in fact a pointer to the function. Only the name of the function is specified
in function arguments.

A very simple and basic example of a callback function is illustrated in the below figure.
A show() function is invoked as a result of onclick event on either of the buttons. This show() function
gets a reference to another function. To display an introduction to AJAX, the respective button is clicked.
This onclick event invokes the show() function and passes introAJAX() as a reference to this function. In
the show function, the received callback reference is invoked and then you will see relevant text
inserted into the empty <div> element created in the webpage. You can further understand the use of a
callback function in the example below:

Using callback functions in AJAX

You can avoid code from cluttering by using callback functions. Instead of creating XMLHttpRequest
object in each separate function and making an AJAX request, you can create a single function with
request and response logic. You can pass any function you desire as a callback, where each function may
contain distinct logic.

Look at a code snippet also described in the video lesson for better understanding of the concept.
Receiving response with responseText and
responseXML
You may recall ResponseText and ResponseXML from previous lesson. In this topic you will see an
example in which the use of both properties is illustrated.

responseText

When the response received through AJAX is in textual format or XML, you can use responseText to read
the response. The text may contain a string with formatted HTML like the one given below.

responseXML

The responseXML property is used when the received response is in XML. Here, you will need to parse
each element one by one depending upon what information you require from the response.

Lesson# 104 – AJAX Case Study


Learning objectives

 Understand AJAX with an example


 Learn to send request and receive response with AJAX

AJAX example
You have become familiarized with important methods and properties relevant to AJAX. You have been
given code snippets to understand each one of them.

Now, you will be given an overview of working with AJAX using an example. This example shows an
implementation of an autocomplete feature. A user types something in an input field and at that time
an event is fired in the backend using AJAX. A list is displayed to the user based on what the user has
typed so far, which contains words that can possibly be the ones the user wants to type.

You can understand the complete example in the video lesson. Some of the important components in
the example code are given below:
 There is an HTML code with an <input> field and an empty <div> to display autocomplete
suggestions.
 loadDoc() is a function, which is invoked as result of oninput() event in the input field. An
XMLHttpRequest object is created in this function and a request is sent with POST method. You
will note that the keyword the user has typed in the input field is passed in send() to be sent to
the server.
 When a response is received the loadCountries() function is called, which populates response
text in the empty <div>.
 A php file with the server-side logic shows how the data is retrieved from a database and a
response is readied as a formatted unordered list <ul>.
 Each list <li> element in the response has an onclick() event associated with it, so that when the
user selects any of the options, it displays the search box.

Lesson# 105 – jQuery Introduction


Learning objectives

 Understanding of the term jQuery

Introduction to jQuery
jQuery is a JavaScript library. It works on the principle of “Write less, do more”. This library is cross
browser compatible, which enables it to run the same in all major web browsers. jQuery is easier to use
as manipulation and traversal of an HTML document, event handling and AJAX are simpler. This library
comes with a number of features such as:

 HTML/DOM manipulation
 CSS manipulation
 Event handlers and utilities
 AJAX
 Animations

You will witness in upcoming lessons that how jQuery has reduced the code you initially had to write
with JavaScript.

Adding jQuery to HTML

To utilize this jQuery library, you need to have it downloaded on your system or add it to your HTML
document. Former way can result in increased load time, however, the later way of adding jQuery to
your document is fast as the copy is cached.

For including jQuery library to your HTML document, you need to add its source in <script> element. You
can know further about the versions of jQuery and the syntax to add this library in the video lesson.
jQuery Content Delivery Network (CDN)

jQuery can be included using jQuery Content Delivery Networks. jQuery is hosted by Microsoft and
Google. You can see sample code for including both libraries in the code snippets below. This again has
faster load time.

Why use jQuery?


It may sound difficult to analyze benefits of using jQuery at this point. However, you will understand in
later lessons that how this library is beneficial in several ways. You will learn about:

 jQuery selectors
 jQuery events
 jQuery effects and jQuery animate
 jQuery HTML , CSS
 jQuery DOM traversal and AJAX

Lesson# 106 – JQuery Syntax


Learning objectives

 Learn basic syntax for performing actions on HTML elements


 Understand document ready event

Basic syntax of a JQuery selector


As was said earlier, jQuery has eased your work and provided an extendable framework. The jQuery
syntax is easier to learn. Consider, for example the selectors you had in JavaScript such as
getElementById to get an HTML element using its id. In jQuery an element can be fetched using its id by
a comparatively simpler notation.

The basic syntax of a jQuery selector looks as follows:

$(selector).action()

 $ denotes jQuery.
 Selector can be id, class, element etc.
 Action indicates what to do with the fetched element

Hence, document.getElementById(“demo”) in jQuery will look like $(“#demo”).


Selectors for various elements

Other selectors can be class, element and this pointer. See the examples below.

 Class

$(".test").hide()

 Element

$("p").hide()

 this pointer

$(this).hide()

The document ready event


jQuery comes with another feature that is the document ready event. This event prevents any jQuery
logic to execute before the document has been completely loaded and readied. You can write your
entire jQuery code in this function, so that once the document is completely ready, only then the jQuery
is executed.

Lesson# 107 – jQuery Selectors


Learning objectives

 Learn the syntax of jQuery selectors

jQuery selectors
You may recall the syntax used for jQuery selectors that is $(selector).action(). To select any HTML
elements using jQuery, multiple selectors exist. Most common of them are given below:

Element selector

To select an HTML element using its tag, you can substitute $(selector) with $(“tag”). For instance, if you
want to access an image <img> element, you can simply write $(“img”).hide().
#id selector

As discussed earlier, you can write $(“#id”) to fetch an element using its unique id. For instance, if you
want to fetch a <div> element using its id=“demo”, you can write $(“#demo”).

.class selector

Similarly, for a class selector, you can specify the class as $(“.class”).

Other jQuery selectors


A number of jQuery selectors exist including the ones discussed in the video lesson. You can study them
on your own. However, you can look at a few of them in the following table with their meanings.

Modularity of code
You can take a note in this lesson that a good practice is to separate your jQuery functions and other
jQuery logic in another file with the extension .js. You can include this file in the <script> element as
the src attribute. In this way, you can easily navigate through your code and modifications will be easier
in the future.

Lesson# 108 – jQuery Traversing


Learning objectives

 Recognize commonly used jQuery selectors


 Learn the use of jQuery selectors to traverse HTML document (DOM)

Traversing the DOM


In large HTML documents with a number of elements, sometimes, you need to filter out desired
elements on the basis of some criteria. jQuery aids you in traversing through the DOM in a number of
ways. There are dedicated methods used with jQuery selectors to filter that selection. For instance, see
the example below:
Figure 1: DOM traver

In Figure 1, the selector is $(“div”), which selects all the <div> elements in the HTML document. Then,
there is the traversing method first() that filters the selection made with $(“div”) and picks only the first
element from the selection. Lastly, the background-color is set to lightgreen for the selected <div>.

Traversing methods

A variety of methods are available in jQuery for DOM traversal. You can look at a few of them in the
following examples.

 first()

Returns the first element from the selected elements.

 last()

Returns the last element from the selected elements.

 eq()

Returns an element with a specific index number of the selected elements.

 filter()

Reduces the set of matched elements to those that match the selector.

 not()

Returns elements that do not match a certain criteria.

DOM element filtering example


An example is illustrated in Figure 2 to give you an idea of how traversing methods are used. Figure 3
shows how the webpage looks like, before jQuery is executed.

Figure 2: Illustration of filtered DOM elements from a selected set


Figure 3: Preview of the webpage before jQuery executes

The change that occurs after executing the script given in Figure 2, is shown in Figure 4.

Figure 4: Element filtering using jQuery

Lesson# 109 – jQuery Events


Learning objectives

 Recognize commonly used jQuery event methods


 Learn the use of jQuery event methods to handle events occurring on DOM elements

jQuery Events
When a user interacts with a webpage, he performs actions like clicking a button, scrolling the webpage,
pressing keys on keyboard, resizing browser window etc. All such actions are responded in one or the
other way. A clicking action on a button with mouse can change its appearance, open a new window or
maybe submit a form.

jQuery provides you with event methods with which you can write responses to actions of a user who
interacts with a webpage.

DOM events
Commonly used DOM events are listed in Table 1. You will learn examples of a few of them in
succeeding lessons.

Table 1: Common DOM events


Writing jQuery event methods

A variety of DOM events can be handled with methods in jQuery. You have seen the list of such methods
in Table 1. You can define a handler for these events that is nothing more than a function, which is
defined to specify the action to be performed when an event fires.

A mouse click event can be written in jQuery as:

To define an action associated with this click event, you can write a function in click().

Lesson# 110 – jQuery Events


Learning objectives

 Recognize commonly used jQuery event methods

DOM Events
You have been introduced with various jQuery events in the previous lesson. You have also learnt how
to add a function to an event. In this lesson, you will look further into these events and learn their use.
Following are some of the DOM events you will be learning in the video lesson.

 ready()

Indicates that the document is completely loaded.

 click()

Indicates a click event when a user clicks on an HTML element.

 dblclick()

Indicates a click event when a user clicks twice (double-clicks) on an HTML element.

 mouseenter()

Executes when the mouse pointer enters an HTML element.

 mouseleave()

Executes when the mouse pointer leaves an HTML element.

 mousedown()
Executes when a mouse button is pressed down, while the mouse is over an HTML element.

 mouseup()

Executes when a mouse button is released, while the mouse is over an HTML element.

 hover()

A combination of mouseenter() and mouseleave(). You will learn its syntax in the video.

 focus()

Indicates that a form field is focused.

 on()

Attaches one or more events with selected HTML elements.

jQuery Events Example


An example is provided in this section, which illustrates the use of aforementioned jQuery events. Figure
1 shows the state of a webpage before any event is fired. On the contrary, Figure 2 shows the changes,
which take effect after every event.

Figure 1: Appearance of webpage b

Figure 2: Changes taking effect after every event.

Reference HTML code is given in Figure 3 for you to understand events occurring in Figure 2.

Figure 3: Reference code for example in Figure 2.

Lesson# 111 – jQuery Effects


Learning objectives

 Recognize commonly used jQuery effects


 Learn the use of jQuery methods to add effects

jQuery Effects
Now that you have learnt jQuery events, you may want to add effects to contents on a webpage. jQuery
facilitates you with methods for adding effects and animations on your webpage. You can hide and show
HTML elements or fade elements. Similarly, sliding effects can be added. All such effects give a visual
appeal to a website.

Some of the commonly used effects are listed below, which will be covered in the video lesson later.

 fadeIn

Gradually changes the opacity for selected elements from hidden to visible.

 fadeout

Gradually changes the opacity for selected elements from visible to hidden.

 fadeToggle

This methods toggles an element between fadeIn() and fadeOut().

 hide

Hides the selected elements.

 show

Shows the hidden selected elements.

 slideUp

Shows an element in a sliding up fashion.

 slideDown

Shows an element in a sliding down fashion.

 slideToggle

This method toggles an element between slideUp() and slideDown().

You will notice later in their syntax that in fading and sliding effects, you will be able to specify speed
and desired effect.
jQuery Effects Example
In this section, you will be able to understand the working of jQuery effects. Given below is a simulation
that will help you in realizing the different effects that can be incorporated in a webpage.

Reference HTML code for above example is provided below. You can try similar examples yourself, to
learn more.

Lesson# 112 – jQuery Effects


Learning objectives

 Recognize commonly used jQuery effects


 Learn the syntax of jQuery methods to add effects

jQuery Effects
An example has been illustrated in previous lesson, showing use of jQuery effects. In this lesson, you will
learn further, how these methods can be used and what are the parameters of each method.

fadeIn() and fadeOut() take three arguments namely, speed. easing and a callback function. You have
studied both methods in preceding lesson. Hide, show(), toggle() and sliding effects will be discussed in
current lesson.

hide, show and toggle effects

The hide() method is used to hide an HTML element. An element once hidden do not take any space in
the document and clears out its occupied space. The show() method is used to set hidden elements to
visible. Any hidden elements take the place and space according to their positioning and hierarchy in the
document. Third method is toggle(), which toggles the current element that is, if it is visible then toggle()
hides it and vice versa.

slideUp, slideDown and slideToggle effects

The slideUp() method is used to slide an element in the upward direction. The element is hidden with
this effect, while, the slideDown() method is used to slide an element in the downward direction. A
hidden element is shown with this effect. On the other hand, slideToggle() toggles an element between
slideUp and slideDown.

Syntax of jQuery Effect Methods


Sliding, hide/show and fading methods (fadeIn, fadeOut and fadeToggle) take three optional arguments.
These arguments are:

 speed

Specifies the speed of the effect.

 easing

Specifies the speed of the element in different points of the animation.

 callback

Specifies the function to be executed after the effect method completes its operation.

On the other hand, fadeTo() method has a somewhat different set of arguments. There is one additional
argument namely, opacity. The value of this argument specifies the value to fade an element to. Its
syntax is as follows:

Lesson# 113 – jQuery Effects


Learning objectives

 Understand jQuery effects with an example

Using a callback function in jQuery effects

Lesson# 114 – jQuery Effects


Learning objectives

 Learn jQuery effects


 Learn methods in the jQuery Math object

The jQuery Math Object


You may have observed that some new methods have been used in the example described in lesson#
113, such as floor() and random(). These methods are part of the jQuery Math object. The jQuery Math
object is used to perform mathematical operations on numeric values. This object comes with a number
of properties. You will have an overview of a few of them in this lesson.

Math floor() and ceil() methods

The floor() method rounds down a given number to its nearest integer. However, ceil() method rounds
up a given number to its nearest integer.

Math random() method

This method returns a random number between the specified range of 0 and 1. However, 0 is inclusive
within the range while 1 is not.

If you want a random integer within a specified range other than 0 to 1, you can take product of the
number returned by random() with the end range. Use floor() to round down that number. See the
example.

If you want to specify a range starting from 1 but not 0 then you can write it as:

Lesson# 115 – jQuery Animate


Learning objectives

 Learn to add animations with jQuery

jQuery Animations
You can add custom animations using jQuery. jQuery provides a method for creating custom animations
and that is animate().

animate() method

The syntax for writing animate() method is:


The method takes arguments, which include key-value pairs to specify CSS properties and their values.
Other optional parameters are the speed of effect and callback function.

Multiple properties can be animated at the same time, which involves almost all properties except color
animation. Color animation is not a part of jQuery library.

Queue functionality
There is an another functionality that comes with animate() that is, queueing of various animate()
methods. If several calls to animate() are written one after the other then they execute one by one in a
sequence as if they are in a queue. Look at the example given below:

stop() method
You may sometimes require to stop an animation while it is halfway through. The stop() method is used
when you want to stop an animation or an effect before its completion.

This method has two optional parameters, the first one specifies whether all animations in the queue
shall be cleared or only the active one. You can set the value to False if you intend to stop active
animation only. Second parameter specifies whether the active animation shall be completed quickly or
not. You can set this value to False if you intend to stop the active animation instantly.

Lesson# 116 – XML Elements


Learning objectives

 Understand XML
 Recognize uses of XML

XML
XML stands for eXtensible Markup Language used in applications and devices to use, store, transport,
and display data. It is both human and machine-readable. What is XML and its application.

A significant feature of XML is that it is self-descriptive. Look at the following XML, which simply shows a
note and it is easily understandable. You can identify the sender and receiver of message as well as the
heading and body of the message.
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

XML Vs HTML
You have been learning HTML from the beginning of the course. You recognized that it is used to display
data on a webpage and determine how the data will look like.

XML on the other hand is used to transmit data over the Internet and describes the data itself. The tags
used in HTML were predefined with the language however, you can add custom tags to your XML.

Advantage of XML
At this point you shall be able to point out a few the advantages of XML. It has not only simplified data
transferring but also ensured platform independence. You can share data over computer systems
independent of the format they are using, as XML stores data as plain text.

Lesson# 117 – jQuery Chaining


Learning objectives

 Understand the chaining technique in jQuery

jQuery Chaining
You have been writing single jQuery statements in a sequence, each new statement following the
previous one. You will be introduced to a new technique of writing multiple jQuery commands
functioning with the same element(s).

When you write a selector with every new jQuery command, the browser takes some time to find those
elements, which meet the criteria. With the technique of chaining you can write multiple commands at a
time for the same selected element(s). Each new action is appended to the preceding one.

Lesson# 118 – JQuery HTML


Learning objectives

 Learn to manipulate DOM elements


DOM get/set content and attributes
You have learnt in previous lessons that jQuery provides you methods for accessing DOM elements
using selectors. With jQuery, you can also Get and Set the contents within these elements and change
them as required. jQuery can help you in manipulating the DOM.

There are a number of methods, which make access and manipulation of the DOM easier. These
methods are:

 text() – This method returns or sets the text in the selected element(s).
 html() – This method returns or sets the content of the selected element(s), which includes the
HTML markup as well.
 val() – This method returns or sets the value of fields in a form.

Similarly, there is a method used to get attribute values and that is attr().

Callback function
To clarify things further, look at the following example. It describes the use of callback function in attr()
method.

You know that the callback function has two parameters. The first parameter shows the index of the
current element in the list of selected elements and the second parameter is the old value of the
attribute.

In the example ahead, an onclick function is defined. When a click event occurs, the attr() method is
used to change the src attribute of <img> element. You will see that the image that is displayed on the
webpage changes when the button is clicked.

Following is the output:

Lesson# 119 – jQuery HTML


Learning objectives

 Learn jQuery methods for adding and removing elements

jQuery Add Elements


jQuery facilitates us with methods for adding and removing elements or their content. Following is the
list of methods for adding a new element/content.

 append() – This method inserts content in the end of the element.


 prepend() – This method inserts content in the beginning of the element.
 after() – This method inserts contents after the element.
 before() – This method inserts content before the element.

The methods after() and before() can be used to add new elements.

jQuery Remove Elements


Following are methods used in jQuery to remove elements or content.

 remove() – This method removes the element entirely along with its child elements.
 empty() – This method removes the child elements of a selected element.

Difference between remove() and empty()


You can easily differentiate between the remove() and empty() methods with the following example
code and its output.

You can see that the remove() method removes the element entirely with its child elements while
empty() clears the contents within the element that clears only the child elements.

Lesson# 120 – jQuery CSS


Learning objectives

 Learn jQuery methods for manipulating CSS

jQuery Manipulating CSS


In this lesson, you will cover another one of the advantages of using jQuery. Manipulating styles of
elements have become easier with jQuery.

There are a number of methods used for CSS manipulation.

 addClass() - Adds one or more classes to the selected elements


 removeClass() - Removes one or more classes from the selected elements
 toggleClass() - Toggles between adding/removing classes from the selected elements
 css() - Sets or returns the style attribute
CSS Manipulation Example
Another example has been put out for you to understand CSS manipulation with jQuery.

See the following code. You can notice that there are three buttons having multiple classes. The first
button Button 1 has classes ‘round’ and ‘purple’. Similarly, Button 2 has classes ‘square’ and purple’.
Lastly, you have Button 3 with classes ‘round’ and ‘purple’.

When Button 1 is clicked, a new class ‘green’ is added to it while on clicking Button 2, its class ‘round’ is
removed and Button 3 toggles between ‘square’ and its default class ‘round’.

Lesson# 121 – jQuery CSS


Learning objectives

 Understand the use of css() method

jQuery css() Method


The jQuery css() method can get or set style properties of selected elements.

 Get a property

To get a CSS property the syntax used is:

 Set a property

To set a specified CSS property, use the following syntax:

For setting multiple properties, you can use the syntax:

Changing style properties with CSS


Another example has been put out for you to understand use of css() method.

The example illustrates getting and setting of style properties using css().
Lesson# 122 – jQuery Dimensions
Learning objectives

 Identify ways of getting and setting dimensions with jQuery

jQuery Methods to get/set Dimensions


jQuery has made it easier to manipulate dimensions of elements in DOM and the Window object.
Methods for working with dimensions are:

 width()
 height()
 innerWidth()
 innerHeight()
 outerWidth()
 outerHeight()

Adjustment to window size – Example


You can adjust content on a webpage according to the size of window. See the following example to
understand this concept.

See the following code, it uses the width() method to find width of the browser window and adjusts the
width of the div according to the change in window’s size. Whatever the size of the window, div adjusts
itself to 50 percent of the window size.

Lesson# 123 – jQuery Traversing


Learning objectives

 Identify relationships between elements in a DOM tree

Traversing the DOM


In previous lessons, you have learnt to traverse down the DOM towards the subsequent elements. In
this lesson, you will be learning DOM traversal in the upward and sideward directions as well.

Most of the tasks performed with jQuery requires traversing of the DOM. You find an element or a set of
elements by providing a selector.
Lesson# 124 – jQuery Traversing
Learning objectives

 Identify ways of traversing the DOM using jQuery methods

jQuery – DOM Traversing Methods


It was discussed in the previous lesson that you can traverse the DOM in the upward and sideward
directions using jQuery.

Finding ancestors of an element

You can find the ancestors of selected element, which can be a parent, grand-parent, great-grandparent
and so on.

Three useful jQuery methods for traversing up the DOM tree are:

 parent() - Returns the direct parent element of the selected element


 parents() - Returns all ancestor elements of the selected element
 parentsUntil() - Returns all ancestor elements between two given arguments

Finding descendants of an element

You can find the descendants of selected element, which can be a child, grand-child or great-grandchild
and so on.

Methods used in jQuery to find descendants are:

 children() - Returns all direct children of the selected element


 find() - Returns descendant elements of the selected element

Lesson# 125 – jQuery Traversing


Learning objectives

 Identify ways for finding siblings of an element

jQuery – DOM Traversing Methods


You can also traverse sideways in a DOM tree to find siblings of an element, which share the same
parent.
Finding siblings of an element

Several useful jQuery methods for traversing sideways in the DOM tree are:

 siblings() - Returns all sibling elements of the selected element


 next() - Returns the next sibling element of the selected element
 nextAll() - Returns all next sibling elements of the selected element
 nextUntil() - Returns all next sibling elements between two given arguments
 prev() - Returns the previous sibling element of the selected element
 prevAll() - Returns all previous sibling elements of the selected element
 prevUntil() - Returns all previous sibling elements between two given arguments

jQuery Filtering
jQuery has facilitated in selecting a specific element based on its position in a group of elements.

jQuery Filtering Methods

You can now simply filter elements from a set of elements using the following jQuery methods:

 first() - Returns the first element of the selected elements


 last() - Returns the last element of the selected elements
 eq() - Returns an element with a specific index number of the selected elements
 filter() - Reduce the set of matched elements to those that match the selector or pass the
function's test
 not() - Returns elements that do not match a certain criteria

Lesson# 126 – jQuery AJAX


Learning objectives

 Learn AJAX with jQuery

jQuery AJAX
As previously discussed in lesson 99, Asynchronous JavaScript And XML, also commonly known as AJAX,
is a technique used in front-end development to create dynamic webpages. However, AJAX has its
unique features such as:

 It allows you to update a webpage without loading the webpage


 Send data to a web server in the background

In this lesson, you will be learning the same concept but with the taste of jQuery methods. With the
jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP
Get and HTTP Post. You can load the external data directly into the selected HTML elements of your web
page.

jQuery load() Method

When you place a request and receive its response using jQuery load(), it loads the data from server and
adds that returned data to your selected element.

jQuery load() used for AJAX and load() event are different. jQuery do not mix these two methods as their
parameters are different.

The syntax is as follows:

 URL: location of resource to load


 data: querystring key/value pairs, optional
 callback: name of callback function, optional

The parameters data and callback are optional.

There are additional parameters to this function that are part of the callback function. These parameters
are:

 responseTxt - contains the resulting content if the call succeeds


 statusTxt - contains the status of the call
 xhr - contains the XMLHttpRequest object

Lesson# 127 – jQuery AJAX


Learning objectives

 Understand HTTP Request and Response using jQuery Get and Post

jQuery – GET and POST


There are two methods in jQuery namely, GET and POST, which are used to implement request-
response between client and server.

get() - Requests data from a specified resource

post() - Submits data to be processed to a specified resource


See the given figure that shows the request and response mechanism with GET and POST methods using
jQuery.

Lesson# 128 – JQuery noConflict


Learning objectives

 Recognize the significance of jQuery noConflict() method

jQuery noConflict()
There exists multiple frameworks of JavaScript like Angular JS, Backbone, Ember etc. So, if you intend to
use jQuery along with other frameworks on your webpages, you may face a conflict on the $ sign. In
order to avoid any conflicts with other frameworks while using the $ sign, you can use the noConflict()
method.

Examples

You have learnt different ways of handling the naming conflicts. You can look at the output of the
examples discussed in the video lesson in the following figure.

You can see that jQuery does not throw any error by noConflict() method.

Lesson# 130 – XML Introduction


Learning objectives

After completing this topic, a student will be able to:

 Describe what is XML


 Describe the Difference between XML and HTML
 Describe about inventions of own XML tags

Is XML a Programming Language?


A programming language consists of grammar rules and its own vocabulary which is used to create
computer programs. These programs instruct the computer to perform specific tasks. XML does not
qualify to be a programming language as it does not perform any computation or algorithms. It is usually
stored in a simple text file and is processed by special software that is capable of interpreting XML.
XML Entities
Like HTML, XML offers methods (called entities) for referring to some special reserved characters (such
as a greater than sign which is used for tags). There are five of these characters that you should know:

XML Does Not DO Anything


Maybe it is a little hard to understand, but XML does not DO anything.

This note is a note to Tove from Jani, stored as XML:

Examle :

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML above is quite self-descriptive:

It has sender information.

It has receiver information

It has a heading

It has a message body.

But still, the XML above does not DO anything. XML is just information wrapped in tags.

Lesson# 131 – XML Usage


Learning objectives

After completing this topic, a student will be able to:

 Describe How can XML be used


 Describe How data can be separate from Presentation
 Complement to HTML
 Transaction Data
What is an XML file?
An XML file is an extensible markup language file, and it is used to structure data for storage and
transport. In an XML file, there are both tags and text. The tags provide the structure to the data. The
text in the file that you wish to store is surrounded by these tags, which adhere to specific syntax
guidelines. At its core, an XML file is a standard text file that utilizes customized tags, to describe the
structure of the document and how it should be stored and transported.

For example, Microsoft Office versions 2007 and later use XML for its document structure. So, when you
save a document in Word, Excel or PowerPoint, you will get the document title with an "X" at the end.
The "X" stands for XML. For a Word document, the title would be presented with ".DOCX" at the end.

XML is a markup language, which means it is a computer language that uses tags to describe
components in a file. This XML markup language contains actual words instead of programming syntax.
The most popular markup languages are HTML and XML. You may already be familiar with HTML, but
XML has a few key differences such as:

 Purpose: With HTML, or hypertext markup language, information is displayed, but with XML that
information is transferred. Typically, HTML is used for encoding web pages. On the other hand,
XML is a language for data-description and is used to store data.

 Ability to customize: HTML uses a pre-selected range of markup symbols or short codes, which
describe the presentation of a web page's content. Conversely, XML is extensible and allows
users to customize and create their own markup symbols. In this way, with XML, users have
complete control and can create an unlimited symbol set to describe their content.

Uses of XML
ML has a variety of uses for Web, e-business, and portable applications.

The following are some of the many applications for which XML is useful:

Web publishing: XML allows you to create interactive pages, allows the customer to customize those
pages, and makes creating e-commerce applications more intuitive. With XML, you store the data once
and then render that content for different viewers or devices based on style sheet processing using an
Extensible Style Language (XSL)/XSL Transformation (XSLT) processor.

Web searching and automating Web tasks: XML defines the type of information contained in a
document, making it easier to return useful results when searching the Web:

For example, using HTML to search for books authored by Tom Brown is likely to return instances of the
term 'brown' outside of the context of author. Using XML restricts the search to the correct context (for
example, the information contained in the <author> tag) and returns only the information that you
want. By using XML, Web agents and robots (programs that automate Web searches or other tasks) are
more efficient and produce more useful results.
General applications: XML provides a standard method to access information, making it easier for
applications and devices of all kinds to use, store, transmit, and display data.

e-business applications: XML implementations make electronic data interchange (EDI) more accessible
for information interchange, business-to-business transactions, and business-to-consumer transactions.

Metadata applications: XML makes it easier to express metadata in a portable, reusable format.

Pervasive computing: XML provides portable and structured information types for display on pervasive
(wireless) computing devices such as personal digital assistants (PDAs), cellular phones, and others. For
example, WML (Wireless Markup Language) and VoiceXML are currently evolving standards for
describing visual and speech-driven wireless device interfaces.

Lesson# 132 – XML Tree


Learning objectives

After completing this topic, a student will be able to:

 Describe XML Tree Structure


 Describe about XML Self-Describing Syntax

What is a Tree?
Tree is a discrete structure that represents hierarchical relationships between individual elements or
nodes.

In mathematics, a tree is a graph in which any two vertices are connected by exactly one simple path.
Any connected graph is a tree. A tree is a hierarchical data structure defined as a collection of nodes. A
hierarchy consists of an order defined on a set. The term hierarchy is used to stress a hierarchical
relation among the elements.

The XML specification defines an XML document as a well-formed text if it satisfies a list of syntax rules
defined in the specification. This specification is long, however 2 key points relating to the tree structure
of an XML document are:

 The begin, end, and empty-element tags that delimit the elements are correctly nested, with
none missing and none overlapping
 A single "root" element contains all the other elements

XML Tree
An XML document is always descriptive. The tree structure is often referred to as XML Tree and plays an
important role to describe any XML document easily.

The tree structure contains root (parent) elements, child elements and so on. By using tree structure,
you can get to know all succeeding branches and sub-branches starting from the root. The parsing starts
at the root, then moves down the first branch to an element, take the first branch from there, and so on
to the leaf nodes.

Example
<?xml version = "1.0"?>

<Company>

<Employee>

<FirstName>Tanmay</FirstName>

<LastName>Patil</LastName>

<ContactNo>1234567890</ContactNo>

<Email>[email protected]</Email>

<Address>

<City>Bangalore</City>

<State>Karnataka</State>

<Zip>560212</Zip>

</Address>

</Employee>

</Company>

Tree Structure Diagram Example


Following tree structure represents the above XML document :

Lesson# 133 – XML Syntax


Learning objectives

After completing this topic, a student will be able to:

 Describe about XML Syntax.


 Describe about XML Syntax Rules.
 Describe about XML Prolog.

XML Introduction
XML (Extensible Markup Language) is a markup language similar to HTML, but without predefined tags
to use. Instead, you define your own tags designed specifically for your needs. This is a powerful way to
store data in a format that can be stored, searched, and shared. Most importantly, since the
fundamental format of XML is standardized, if you share or transmit XML across systems or platforms,
either locally or over the internet, the recipient can still parse the data due to the standardized XML
syntax.

There are many languages based on XML, including XHTML, MathML, SVG, XUL, XBL, RSS, and RDF.

Syntax of a programming language


The syntax of a computer language is the set of rules that defines the combinations of symbols that are
considered to be correctly structured statements or expressions in that language. This applies both to
programming languages, where the document represents source code, and to markup languages, where
the document represents data.

The syntax of a language defines its surface form.[1] Text-based computer languages are based on
sequences of characters, while visual programming languages are based on the spatial layout and
connections between symbols (which may be textual or graphical). Documents that are syntactically
invalid are said to have a syntax error.

XML Syntax Rules


You must follow these rules when you create XML syntax:

 All XML elements must have a closing tag.


 XML tags are case sensitive.
 All XML elements must be properly nested.
 All XML documents must have a root element.
 Attribute values must always be quoted.

Example
<?xml version = "1.0"?>
<contact-info>

<name>Tanmay Patil</name>

<company>TutorialsPoint</company>

<phone>(011) 123-4567</phone>

</contact-info>

Diagram Example
You can notice there are two kinds of information in the above example.

 Markup, like <contact-info>


 The text, or the character data, Tutorials Point and (040) 123-4567.

The following diagram depicts the syntax rules to write different types of markup and text in an XML
document.

Lesson# 134 – HTML Canvas Gradients

Learning objectives

After completing this topic, a student will be able to:

 Create Linear Gradient.


 Create Radial Gradient.

Canvas Introduction

Canvas is an extremely durable plain-woven fabric used for


making sails, tents, marquees, backpacks, shelters, as a support
for oil painting and for other items for which sturdiness is
required, as well as in such fashion objects as handbags,
electronic device cases, and shoes. It is also popularly used by
artists as a painting surface, typically stretched across a
wooden frame.

Modern canvas is usually made of cotton or linen, or sometimes


polyvinyl chloride (PVC), although historically it was made from
hemp. It differs from other heavy cotton fabrics, such as denim,
in being plain weave rather than twill weave. Canvas comes in
two basic types: plain and duck. The threads in duck canvas are
more tightly woven. The term duck comes from the Dutch word
for cloth, doek. In the United States, canvas is classified in two
ways: by weight (ounces per square yard) and by a graded
number system. The numbers run in reverse of the weight so a
number 10 canvas is lighter than number 4. Canvas has become
the most common support medium for oil painting, replacing
wooden panels. It was used from the 14th century in Italy, but
only rarely. One of the earliest surviving oils on canvas is a
French Madonna with angels from around 1410 in the
Gemäldegalerie, Berlin.

Linear Gradient Example

Following is a simple example which makes use of above


mentioned methods to create Linear gradient.

Example

<html>

<head>
<style>

#test {

width:100px;

height:100px;

margin:0px auto;

</style>

<script type = "text/javascript">

function drawShape() {

// get the canvas element using the DOM

var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't


supported

if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Create Linear Gradients

var lingrad = ctx.createLinearGradient(0,0,0,150);

lingrad.addColorStop(0, '#00ABEB');

lingrad.addColorStop(0.5, '#fff');

lingrad.addColorStop(0.5, '#66CC00');

lingrad.addColorStop(1, '#fff');

var lingrad2 = ctx.createLinearGradient(0,50,0,95);

lingrad2.addColorStop(0.5, '#000');
lingrad2.addColorStop(1, 'rgba(0,0,0,0)');

// assign gradients to fill and stroke styles

ctx.fillStyle = lingrad;

ctx.strokeStyle = lingrad2;
// draw shapes

ctx.fillRect(10,10,130,130);

ctx.strokeRect(50,50,50,50);

} else {

alert('You need Safari or Firefox 1.5+ to see this


demo.');

</script>

</head>

<body id = "test" onload = "drawShape();">

<canvas id = "mycanvas"></canvas>

</body>

</html>

Lesson# 135 – XML Attributes


Learning objectives

After completing this topic, a student will be able to:


 Describe about XML Attributes.
 Describe about rules of writing XML Attributes.
 Describe about the difference between XML Elements vs. Attributes
 Describe about XML Attributes for Metadata

XML Introduction
XML (Extensible Markup Language) is a markup language similar to HTML, but without predefined tags
to use. Instead, you define your own tags designed specifically for your needs. This is a powerful way to
store data in a format that can be stored, searched, and shared. Most importantly, since the
fundamental format of XML is standardized, if you share or transmit XML across systems or platforms,
either locally or over the internet, the recipient can still parse the data due to the standardized XML
syntax.

There are many languages based on XML, including XHTML, MathML, SVG, XUL, XBL, RSS, and RDF.

Attribute of a programming language


An attribute is a markup construct consisting of a name–value pair that exists within a start-tag or
empty-element tag. An example is <img src="madonna.jpg" alt="Madonna" />, where the names of the
attributes are "src" and "alt", and their values are "madonna.jpg" and "Madonna" respectively. Another
example is <step number="3">Connect A to B.</step>, where the name of the attribute is "number" and
its value is "3". An XML attribute can only have a single value and each attribute can appear at most
once on each element. In the common situation where a list of multiple values is desired, this must be
done by encoding the list into a well-formed XML attribute[i] with some format beyond what XML
defines itself. Usually this is either a comma or semi-colon delimited list or, if the individual values are
known not to contain spaces,[ii] a space-delimited list can be used. <div class="inner greeting-
box">Welcome!</div>, where the attribute "class" has both the value "inner greeting-box" and also
indicates the two CSS class names "inner" and "greeting-box".

XML Attributes
The XML attribute is a part of an XML element. The addition of attribute in XML element gives more
precise properties of the element i.e., it enhances the properties of the XML element.

Syntax:

<element_name attribute1 attribute2 ... > Contents... </element_name>

In the above syntax element_name is the name of an element which can be any name.
The attribute1, attribute2, … is XML attribute having unique attribute name. Then in the
content section, any message can be written and at the end, the element name is
ended.

Attribute Types:
There are three types of attributes described below:

 String types Attribute: This type of attribute takes any string literal as a value.
 Enumerated Type Attribute: This attribute is further distributed in two types-

1. Notation Type: This attribute is used to declares that an element will be referenced to a notation
which is declared somewhere else in the XML document.
2. Enumeration: This attribute is used to specify a particular list of values which match with
attribute values.

 Tokenized Type Attribute: This attribute is further distributed in many types:

1. ID: This attribute is used to identify the element.


2. IDREF: This attribute is used to refer an ID which has already been named for another element.
3. IDREFS: This attribute is used to refer all IDs of an element.
4. ENTITY: This attribute is used to indicate the attribute which will represent an external entity
used in the document.
5. ENTITIES: This attribute is used to indicate the attribute which will represent external entities
used in the document.

Lesson# 136 – XML NameSpaces


Learning objectives

After completing this topic, a student will be able to:

 Describe about Name Conflicts in XML


 Describe about Solving the Name Conflicts in XML.
 Describe about XML Namespaces
 Describe about Uniform Resource Identifier (URI)
 Describe about Default Namespaces
 Describe about Namespaces in Real Use

What are Namesapces


In computing, a namespace is a set of signs (names) that are used to identify and refer to objects of
various kinds. A namespace ensures that all of a given set of objects have unique names so that they can
be easily identified.

Namespaces are commonly structured as hierarchies to allow the reuse of names in different contexts.
As an analogy, consider a system of the naming of people where each person has a given name, as well
as a family name shared with their relatives. If the first names of family members are unique only within
each family, then each person can be uniquely identified by the combination of first name and family
name; there is only one Jane Doe, though there may be many Janes. Within the namespace of the Doe
family, just "Jane" suffices to unambiguously designate this person, while within the "global" namespace
of all people, the full name must be used.

What is W3C
The World Wide Web Consortium (W3C) is the main international standards organization for the World
Wide Web. Founded in 1994 and currently led by Tim Berners-Lee, the consortium is made up of
member organizations that maintain full-time staff working together in the development of standards
for the World Wide Web. As of 21 October 2019, W3C had 443 members.[3][2] W3C also engages in
education and outreach, develops software and serves as an open forum for discussion about the Web.

Namespace Declaration
Namespace is declared using reserved attributes. Such an attribute name must either be xmlns or begin
with xmlns: shown as below −

<element xmlns:name = "URL">

Syntax:

<element_name attribute1 attribute2 ... > Contents... </element_name>

xx. The Namespace starts with the keyword xmlns.

xx. The word name is the Namespace prefix.

xx. The URL is the Namespace identifier.

Example
Namespace affects only a limited area in the document. An element containing the declaration and all of
its descendants are in the scope of the Namespace. Following is a simple example of XML Namespace −

<?xml version = "1.0" encoding = "UTF-8"?>

<cont:contact xmlns:cont = "www.tutorialspoint.com/profile">

<cont:name>Tanmay Patil</cont:name>

<cont:company>TutorialsPoint</cont:company>

<cont:phone>(011) 123-4567</cont:phone>

</cont:contact>
Here, the Namespace prefix is cont, and the Namespace identifier (URI) as
www.tutorialspoint.com/profile. This means, the element names and attribute names with the cont
prefix (including the contact element), all belong to the www.tutorialspoint.com/profile namespace.

Lesson# 137 – XML DTD


Learning objectives

After completing this topic, a student will be able to:

 Describe about DTD


 Describe about XML DTD
 Describe about Valid XML Documents
 Describe about Using DTD for Entity Declaration
 Describe about Why to Use DTD

What is DTD
A document type definition (DTD) is a set of markup declarations that define a document type for an
SGML-family markup language (GML, SGML, XML, HTML).

A DTD defines the valid building blocks of an XML document. It defines the document structure with a
list of validated elements and attributes. A DTD can be declared inline inside an XML document, or as an
external reference.[1]

XML uses a subset of SGML DTD.

As of 2009, newer XML namespace-aware schema languages (such as W3C XML Schema and ISO RELAX
NG) have largely superseded DTDs. A namespace-aware version of DTDs is being developed as Part 9 of
ISO DSDL. DTDs persist in applications that need special publishing characters, such as the XML and
HTML Character Entity References, which derive from larger sets defined as part of the ISO SGML
standard effort.

Checking Validation before proceeding with XML DTD


Before proceeding with XML DTD, you must check the validation. An XML document is called "well-
formed" if it contains the correct syntax.

A well-formed and valid XML document is one which have been validated against DTD.

Visit http://www.xmlvalidation.com to validate the XML file.

In above link, you can copy your XML code and it will check validation for you.

XML DTD with entity declaration


A doctype declaration can also define special strings that can be used in the XML file.

An entity has three parts:

An ampersand (&)

An entity name

A semicolon (;)

Syntax to declare entity:

<!ENTITY entity-name "entity-value">

Let's see a code to define the ENTITY in doctype declaration.

author.xml

<?xml version="1.0" standalone="yes" ?>

<!DOCTYPE author [

<!ELEMENT author (#PCDATA)>

<!ENTITY sj "Sonoo Jaiswal">

]>

<author>&sj;</author>

In the above example, sj is an entity that is used inside the author element. In such case, it will print the
value of sj entity that is "Sonoo Jaiswal".

Lesson# 138 – XML Schema


Learning objectives

After completing this topic, a student will be able to:

 Describe about XML Schema


 Describe about Comparison between XML Schema and XML DTD
 Describe about Datatypes supported by XML Schema

What is Schema
In computer programming, a schema (pronounced SKEE-mah) is the organization or structure for a
database, while in artificial intelligence (AI) a schema is a formal expression of an inference rule.

For the former, the activity of data modeling leads to a schema. In the latter, a schema is derived from
mathematics and is -- essentially -- a generalized axiom or expression where specific values or cases are
substituted for symbols in a hypothesis to derive a particular inference.

The word schema originates in the Greek word for form or figure. However, how you specifically define
schema depends on context. There are different types of schemas, and their meanings are closely
related to fields like data science, education, marketing and SEO (search engine optimization) and
psychology.

An XML Schema is a language for expressing constraints about XML documents. There are several
different schema languages in widespread use, but the main ones are Document Type Definitions
(DTDs), Relax-NG, Schematron and W3C XSD (XML Schema Definitions).

What is XML Schema Used For?


A Schema can be used:

 to provide a list of elements and attributes in a vocabulary;

 to associate types, such as integer, string, etc., or more specifically such as hatsize, sock_colour,
etc., with values found in documents;

 to constrain where elements and attributes can appear, and what can appear inside those
elements, such as saying that a chapter title occurs inside a chapter, and that a chapter must
consist of a chapter title followed by one or more paragraphs of text;

 to provide documentation that is both human-readable and machine-processable;

 to give a formal description of one or more documents.

Information in schema documents is often used by XML-aware editing systems so that they can offer
users the most likely elements to occur at any given location in a document.

Checking a document against a Schema is known as validating against that schema; for a DTD, this is just
validating, but for any other type of schema the type is mentioned, such as XSD Validation or Relax-NG
validation.

Validating against a schema is an important component of quality assurance.

The Service Modeling Language (SML) provides a framework for relating multiple XSD documents to one
or more documents in a single validation episode.
Since XSD supports associating data types with element and attribute content, it is also used for data
binding, that is, for software components that read and write XML representations of computer
programming-language objects.

Lesson# 139 – XSLT (eXtensible Style sheet Language


Transformation)
Learning objectives

After completing this topic, a student will be able to:

 Describe about XSLT


 Describe about how XSLT works

Some History Of XSLT


XSLT is influenced by functional languages, and by text-based pattern matching languages like SNOBOL
and AWK. Its most direct predecessor is DSSSL, which did for SGML what XSLT does for XML.

XSLT 1.0: XSLT was part of the World Wide Web Consortium (W3C)'s eXtensible Stylesheet Language
(XSL) development effort of 1998–1999, a project that also produced XSL-FO and XPath. Some members
of the standards committee that developed XSLT, including James Clark, the editor, had previously
worked on DSSSL. XSLT 1.0 was published as a W3C recommendation in November 1999. Despite its age,
XSLT 1.0 is still widely used (as of 2018), since later versions are not supported natively in web browsers
or for environments like LAMP.

XSLT 2.0: after an abortive attempt to create a version 1.1 in 2001, the XSL working group joined forces
with the XQuery working group to create XPath 2.0, with a richer data model and type system based on
XML Schema. Building on this is XSLT 2.0, developed under the editorship of Michael Kay, which reached
recommendation status in January 2007. The most important innovations in XSLT 2.0 include:

 String manipulation using regular expressions

 Functions and operators for manipulating dates, times, and durations

 Multiple output documents

 Grouping (creating hierarchic structure from flat input sequences)

 A richer type system and stronger type checking

Main Parts of XSL


Following are the main parts of XSL −:
 XSLT − used to transform XML document into various other types of document.
 XPath − used to navigate XML document.
 XSL-FO − used to format XML document.

How XSLT Works


An XSLT stylesheet is used to define the transformation rules to be applied on the target XML document.
XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT stylesheet and applies the
transformation rules on the target XML document and then it generates a formatted document in the
form of XML, HTML, or text format. This formatted document is then utilized by XSLT formatter to
generate the actual output which is to be displayed to the end-user.

Lesson# 140 – HTML5 - audio


Learning objectives

After completing this topic, a student will be able to:

 Describe about Different Browsers Support for HTML Audio


 Describe about Methods, Properties and Events in HTML Audio

What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see, like images,
music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and formats.

Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.

The most common way to discover the type of a file, is to look at the file extension.

Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Lesson# 141 – XPath


Learning objectives

After completing this topic, a student will be able to:


 Describe about XPath
 Describe about XPath Path Expressions
 Describe about usage of XPath in XSLT
 Describe about XPath Expressions

XSLT Introduction
EXtensible Stylesheet Language Transformation commonly known as XSLT is a way to transform the XML
document into other formats such as XHTML.

An XSLT stylesheet is used to define the transformation rules to be applied on the target XML document.
XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT stylesheet and applies the
transformation rules on the target XML document and then it generates a formatted document in the
form of XML, HTML, or text format.

XPath is a W3C Recommendation


 XPath 1.0 became a W3C Recommendation on November 16, 1999.

 XPath 2.0 became a W3C Recommendation on January 23, 2007.

 XPath 3.0 became a W3C Recommendation on April 8, 2014.

Lesson# 142 – XLink & XPointer


Learning objectives

After completing this topic, a student will be able to:

 Describe about XLink and its Syntax


 Describe about XLink major attributes
 Describe about XPointer

What is XML?
xx. XML stands for eXtensible Markup Language

xx. XML is a markup language much like HTML

xx. XML was designed to store and transport data

xx. XML was designed to be self-descriptive

xx. XML is a W3C Recommendation


Linking with XLink
Link defines a set of attributes that may be added to elements of other XML namespaces. XLink
provides two kinds of hyperlinking for use in XML documents. Simple links connect only two resources,
similar to HTML links. Extended links can link an arbitrary number of resources.

Simple links

A simple link creates a unidirectional hyperlink from one element to another via a URI.

Example:

<?xml version="1.0"?>

<document xmlns="http://example.org/xmlns/2002/document"
xmlns:xlink="http://www.w3.org/1999/xlink">

<heading id="someHeading">Some Document</heading>

<para>Here is <anchor xlink:type="simple" xlink:href="#someHeading">a link</anchor> to the


header.</para>

<para>It is an anchor that points to the element with the id "someHeading" on the current
page.</para>

</document>

Extended links
Extended links allow multiple resources, either remote or local, to be connected by multiple arcs. An arc
is information about the origin, destination and behavior of a link between two resources. The origin
and destination resources are defined by labels. By using one or more arcs, an extended link can achieve
specific sets of connections between multiple resources.

For example, if all resources in an extended link were given the label A, then an arc within that link
declaring from="A", to="A" would form connections between all resources.

Extended links do not need to be contained in the same document as the elements they link to. This
makes it possible to associate metadata or other supplementary information with resources without
editing those resources.

XLink also supports richer information about link types and the roles of each resource in an arc.

Positional Element Addressing


The element() scheme[7] introduces positional addressing of child elements. This is similar to a simple
XPath address, but subsequent steps can only be numbers representing the position of a descendant
relative to its branch on the tree.

For instance, given the following fragment:

<foobar id="foo">

<bar/>

<baz>

<bom a="1"/>

</baz>

<bom a="2"/>

</foobar>

Results as the following examples:

xpointer(id("foo")) => foobar

xpointer(/foobar/1) => bar

xpointer(//bom) => bom (a=1), bom (a=2)

element(/1/2/1) => bom (a=1) (/1 descend into first element (foobar),

/2 descend into second child element (baz),

/1 select first child element (bom))

Lesson# 143 – JSON Introduction


Learning objectives

After completing this topic, a student will be able to:

 Describe about JSON


 Describe about Comparison of JSON and XML
 Describe about Why should we use JSON

History of JSON
JSON grew out of a need for stateless, real-time server-to-browser communication protocol without
using browser plugins such as Flash or Java applets, the dominant methods used in the early 2000s.

A precursor to the JSON libraries was used in a children's digital asset trading game project named
Cartoon Orbit at Communities.com (at which State Software's co-founders had all worked previously) for
Cartoon Network, which used a browser side plug-in with a proprietary messaging format to manipulate
Dynamic HTML elements (this system is also owned by 3DO). Upon discovery of early Ajax capabilities,
digiGroups, Noosh, and others used frames to pass information into the user browsers' visual field
without refreshing a Web application's visual context, realizing real-time rich Web applications using
only the standard HTTP, HTML and JavaScript capabilities of Netscape 4.0.5+ and IE 5+.

Crockford first specified and popularized the JSON format. The State Software co-founders agreed to
build a system that used standard browser capabilities and provided an abstraction layer for Web
developers to create stateful Web applications that had a persistent duplex connection to a Web server
by holding two Hypertext Transfer Protocol (HTTP) connections open and recycling them before
standard browser time-outs if no further data were exchanged. The co-founders had a round-table
discussion and voted whether to call the data format JSML (JavaScript Markup Language) or JSON
(JavaScript Object Notation), as well as under what license type to make it available. Chip Morningstar
developed the idea for the State Application Framework at State Software.

The system was sold to Sun Microsystems, Amazon.com and EDS. The JSON.org website was launched in
2002. In December 2005, Yahoo! began offering some of its Web services in JSON.

JSON was based on a subset of the JavaScript scripting language (specifically, Standard ECMA-262 3rd
Edition—December 1999[15]) and is commonly used with JavaScript, but it is a language-independent
data format. Code for parsing and generating JSON data is readily available in many programming
languages. JSON's website lists JSON libraries by language.

In October 2013, Ecma International published the first edition of its JSON standard ECMA-404. That
same year, RFC 7158 used ECMA-404 as a reference. In 2014, RFC 7159 became the main reference for
JSON's Internet uses, superseding RFC 4627 and RFC 7158 (but preserving ECMA-262 and ECMA-404 as
main references). In November 2017, ISO/IEC JTC 1/SC 22 published ISO/IEC 21778:2017 as an
international standard. On 13 December 2017, the Internet Engineering Task Force obsoleted RFC 7159
when it published RFC 8259, which is the current version of the Internet Standard STD 90.

Comparison of JSON with other formats


JSON is promoted as a low-overhead alternative to XML as both of these formats have widespread
support for creation, reading, and decoding in the real-world situations where they are commonly used.
[54] Apart from XML, examples could include CSV and YAML (a superset of JSON). Also, Google Protocol
Buffers can fill this role, although it is not a data interchange language.

YAML

YAML version 1.2 is a superset of JSON; prior versions were not strictly compatible. For example,
escaping a slash / with a backslash \ is valid in JSON, but was not valid in YAML. YAML supports
comments, while JSON does not.
XML

XML has been used to describe structured data and to serialize objects. Various XML-based protocols
exist to represent the same kind of data structures as JSON for the same kind of data interchange
purposes. Data can be encoded in XML in several ways. The most expansive form using tag pairs results
in a much larger representation than JSON, but if data is stored in attributes and 'short tag' form where
the closing tag is replaced with />, the representation is often about the same size as JSON or just a little
larger. However, an XML attribute can only have a single value and each attribute can appear at most
once on each element.

XML separates "data" from "metadata" (via the use of elements and attributes), while JSON does not
have such a concept.

Another key difference is the addressing of values. JSON has objects with a simple "key" to "value"
mapping, whereas in XML addressing happens on "nodes", which all receive a unique ID via the XML
processor. Additionally, the XML standard defines a common attribute xml:id, that can be used by the
user, to set an ID explicitly.

XML tag names cannot contain any of the characters !"#$%&'()*+,/;<=>?@[\]^`{|}~, nor a space
character, and cannot begin with -, ., or a numeric digit, whereas JSON keys can (even if quotation mark
and backslash must be escaped).

XML values are strings of characters, with no built-in type safety. XML has the concept of schema, that
permits strong typing, user-defined types, predefined tags, and formal structure, allowing for formal
validation of an XML stream. JSON has strong typing built-in, and has a similar schema concept in JSON
Schema.

XML supports comments, while JSON does not.

JSON file can be converted to XML (and back) using online file converters.

Lesson# 144 – JSON Syntax


Learning objectives

After completing this topic, a student will be able to:

 Describe about JSON Syntax Rules


 Describe about JSON Values
 Describe about JSON Objects
 Describe about JSON Arrays
 JSON Parsing

Syntax of a Programming Language


Syntax refers to the rules that define the structure of a language. Syntax in computer programming
means the rules that control the structure of the symbols, punctuation, and words of a programming
language.

Without syntax, the meaning or semantics of a language is nearly impossible to understand.

For example, a series of English words, such as — subject a need and does sentence a verb — has little
meaning without syntax.

Applying basic syntax results in the sentence — Does a sentence need a subject and verb?

Programming languages function on the same principles.

If the syntax of a language is not followed, the code will not be understood by a compiler or interpreter.

Generating and Parsing JSON Data


For generating and parsing JSON data, there are two programming models, which are similar to those
used for XML documents.

The object model creates a tree that represents the JSON data in memory. The tree can then be
navigated, analyzed, or modified. This approach is the most flexible and allows for processing that
requires access to the complete contents of the tree. However, it is often slower than the streaming
model and requires more memory. The object model generates JSON output by navigating the entire
tree at once.

The streaming model uses an event-based parser that reads JSON data one element at a time. The
parser generates events and stops for processing when an object or an array begins or ends, when it
finds a key, or when it finds a value. Each element can be processed or discarded by the application
code, and then the parser proceeds to the next event. This approach is adequate for local processing, in
which the processing of an element does not require information from the rest of the data. The
streaming model generates JSON output to a given stream by making a function call with one element at
a time.

There are many JSON generators and parsers available for different programming languages and
environments.

Lesson# 146 – HTML5 Introduction


Learning objectives

After completing this topic, a student will be able to:

 Describe about History of HTML


 Describe about HTML5 Introduction
 Descre about New HTML5 Elements
 Describe about New HTML5 API’s
 Describe about Elements removed in HTML5

Different Versions of HTML


1. HTML 1.0

The basic version of HTML has support for basic elements like text controls and images. This was the
very basic version of HTML with less support for a wide range of HTML elements. It does not have rich
features like styling and other things that were related to how content will be rendered in a browser.

The initial version of HTML does not provide support for tables, font support, etc., as it provides us in
the latest version.

We would also like to discuss that W3C did not exist before HTML 2.0; hence it does not show details
about HTML 1.

2. HTML 2

HTML version 2.0 was developed in 1995 with basic intention of improving HTML version 1.0

Now a standard got started to develop so as to maintain common rules and regulations across different
browsers. HTML 2.0 has improved a lot in terms of the markup tags. In HTML 2.0 version concept of
form came into force. Forms were developed, but still, they had basic tags like text boxes, buttons, etc.

Also, the table came as an HTML tag. Now, in HTML tag 2.0, browsers also came with the concept of
creating their own layers of tags that were specific to the browser itself. W3C was also formed. The main
intention of W3C is to maintain standard across different web browsers so that these browsers
understand and render HTML tags in a similar manner.

3. HTML 3.2

It was developed in 1997. After HTML 2.0 was developed, the next version of HTML was 3.2

With version 3.2 of HTML, HTML tags were further improved. It is worth noting that because of W3C
standard maintenance, the newer version of HTML was 3.2 instead of 3.

Now, HTML 3.2 has better support for new form elements. Another important feature what HTML 3.2
implemented was support for CSS. CSS stands for Cascading Style Sheet. It is CSS that provides features
to make HTML tags look better on rendering it on browsers. CSS helps to style HTML elements.

With the upgradation of browsers to HTML 3.2, the browser also supported for frame tags, although
HTML specifications still do not support frame markup tags.

4. HTML 4.01
It was developed in 1999. It extended the support of cascading styling sheets. In version 3.2, CSS were
embedded in HTML page itself. Therefore, if the website has various web pages to apply to the style of
each page, we must place CSS on each web page. Hence there was a repetition of the same block of CSS.

To overcome this thing, in version 4.01 concept of an external styling sheet emerged. Under this
concept, an external CSS file could be developed, and this external styling file could be included in HTML
itself. HTML 4.01 provided support for further new tags of HTML.

5. HTML5

This is the latest version of HTML. For a developer, it could be used in 2014. It came up with lots of
HTML tags support. HTML5 provided support for new form elements like input element s of different
types; geolocations support tags, etc.

Let us look at a few of the tags which were added to HTML5

Email – New HTML5 tag, which was added, is the input element of type email. This is a form tag,
although it could be used outside of a form tag also. This tag checks the validation of the input value. It
checks whether the value inserted is a valid email.

Password – This is another form tag that was added to receive a password from the user. Being the
password type field, the user types in the field are not visible directly to the user but are represented by
special symbols. These symbols save the password from getting revealed on the browser.

Audio tag – This is a new audio tag that was implemented in HTML5. This tag helps to add audio to our
web page. We can use this tag to embed an audio clip into a web page. This audio tag could be played
on a webpage.

Semantic tags – Semantic tags are also known as structural tags. Structural tags are the tags that provide
structure to the HTML page. It helps it divide the HTML page into different structures. These structures
get combined into an HTML page itself to form an HTML web page. Few of the important HTML
semantic tags are figcaption, <header>, <footer>

Section tag – This tag is used to semantic a section in an HTML page. A section tag represents a section
on a web page.

6. W3C HTML Validator

An HTML validator is a web-based tool that is used to maintain or check whether a piece of HTML tag or
HTML is valid. An HTML validator follows the standard of W3C to validate an HTML page. It follows the
W3C standard.

HTML5 Content Models


In HTML5, the content of a web page can be divided into semantic groups, which describe its content.
These groups are called content models. Each of these models describes the type of elements it
contains. The content model can contain text and child elements. The element can belong to one or
more content categories.

HTML5 content models are listed below:

 Metadata content
 Flow content
 Sectioning content
 Heading content
 Phrasing content
 Embedded content
 Interactive content
 Palpable content

Content models can overlap, and it means that elements are belonging to several categories in the
meantime. For example, sectioning, heading, phrasing, embedded, interactive, and a part of metadata
content refer to flow content. Metadata and interactive content in certain cases may refer to phrasing
content.

Lesson# 147 – HTML5 Elements


Learning objectives

After completing this topic, a student will be able to:

 Describe about New Elements in HTML5


 Describe about New Semantic/Structural Elements
 Describe about New Form Elements in HTML5
 Describe about New Attribute Syntax in HTML5
 Describe about HTML5 Graphics

What is an Element
An HTML element is an individual component of an HTML document. It represents semantics, or
meaning. For example, the title element represents the title of the document.

Most HTML elements are written with a start tag (or opening tag) and an end tag (or closing tag), with
content in between. Elements can also contain attributes that defines its additional properties. For
example, a paragraph, which is represented by the p element, would be written as:

HTML Tags Vs Elements


Technically, an HTML element is the collection of start tag, its attributes, an end tag and everything in
between. On the other hand an HTML tag (either opening or closing) is used to mark the start or end of
an element, as you can see in the above illustration.

However, in common usage the terms HTML element and HTML tag are interchangeable i.e. a tag is an
element is a tag. For simplicity's sake of this website, the terms "tag" and "element" are used to mean
the same thing — as it will define something on your web page.

Alphabetical List of HTML5 Tags/Elements


The following section contains a complete list of standard tags belonging to the latest HTML5 and
XHTML 1.1 specifications. All the tags are listed alphabetically.

Tag Description
<a> Defines a hyperlink.
<abbr> Defines an abbreviated form of a longer word or phrase.
<acronym> Obsolete Defines an acronym. Use <abbr> instead.
<address> Specifies the author's contact information.
<applet> Obsolete Embeds a Java applet (mini Java applications) on the page. Use <object> instead.
<area> Defines a specific area within an image map.
<article> Defines an article.
<aside> Defines some content loosely related to the page content.
<audio> Embeds a sound, or an audio stream in an HTML document.
<b> Displays text in a bold style.
<base> Defines the base URL for all relative URLs in a document.
<basefont> Obsolete Specifies the base font for a page. Use CSS instead.
<bdi> Represents text that is isolated from its surrounding for the purposes of bidirectional text formattin
<bdo> Overrides the current text direction.
<big> Obsolete Displays text in a large size. Use CSS instead.
<blockquote> Represents a section that is quoted from another source.
<body> Defines the document's body.
<br> Produces a single line break.
<button> Creates a clickable button.
<canvas> Defines a region in the document, which can be used to draw graphics on the fly via scripting (usual
JavaScript).
<caption> Defines the caption or title of the table.
<center> Obsolete Align contents in the center. Use CSS instead.
<cite> Indicates a citation or reference to another source.
<code> Specifies text as computer code.
<col> Defines attribute values for one or more columns in a table.
<colgroup> Specifies attributes for multiple columns in a table.
<data> Links a piece of content with a machine-readable translation.
Tag Description
<datalist> Represents a set of pre-defined options for an <input> element.
<dd> Specifies a description, or value for the term (<dt>) in a description list (<dl>).
<del> Represents text that has been deleted from the document.
<details> Represents a widget from which the user can obtain additional information or controls on-demand.
<dfn> Specifies a definition.
<dialog> Defines a dialog box or subwindow.
<dir> Obsolete Defines a directory list. Use <ul> instead.
<div> Specifies a division or a section in a document.
<dl> Defines a description list.
<dt> Defines a term (an item) in a description list.
<em> Defines emphasized text.
<embed> Embeds external application, typically multimedia content like audio or video into an HTML docume
<fieldset> Specifies a set of related form fields.
<figcaption> Defines a caption or legend for a figure.
<figure> Represents a figure illustrated as part of the document.
<font> Obsolete Defines font, color, and size for text. Use CSS instead.
<footer> Represents the footer of a document or a section.
<form> Defines an HTML form for user input.
<frame> Obsolete Defines a single frame within a frameset.
<frameset> Obsolete Defines a collection of frames or other frameset.
<head> Defines the head portion of the document that contains information about the document such as ti
<header> Represents the header of a document or a section.
<hgroup> Defines a group of headings.
<h1> to <h6> Defines HTML headings.
<hr> Produce a horizontal line.
<html> Defines the root of an HTML document.
<i> Displays text in an italic style.
<iframe> Displays a URL in an inline frame.
<img> Represents an image.
<input> Defines an input control.
<ins> Defines a block of text that has been inserted into a document.
<kbd> Specifies text as keyboard input.
<keygen> Represents a control for generating a public-private key pair.
<label> Defines a label for an <input> control.
<legend> Defines a caption for a <fieldset> element.
<li> Defines a list item.
<link> Defines the relationship between the current document and an external resource.
<main> Represents the main or dominant content of the document.
<map> Defines a client-side image-map.
<mark> Represents text highlighted for reference purposes.
Tag Description
<menu> Represents a list of commands.
<menuitem> Defines a list (or menuitem) of commands that a user can perform.
<meta> Provides structured metadata about the document content.
<meter> Represents a scalar measurement within a known range.
<nav> Defines a section of navigation links.
<noframes> Obsolete Defines an alternate content that displays in browsers that do not support frames.
<noscript> Defines alternative content to display when the browser doesn't support scripting.
<object> Defines an embedded object.
<ol> Defines an ordered list.
<optgroup> Defines a group of related options in a selection list.
<option> Defines an option in a selection list.
<output> Represents the result of a calculation.
<p> Defines a paragraph.
<param> Defines a parameter for an object or applet element.
<picture> Defines a container for multiple image sources.
<pre> Defines a block of preformatted text.
<progress> Represents the completion progress of a task.
<q> Defines a short inline quotation.
<rp> Provides fall-back parenthesis for browsers that that don't support ruby annotations.
<rt> Defines the pronunciation of character presented in a ruby annotations.
<ruby> Represents a ruby annotation.
<s> Represents contents that are no longer accurate or no longer relevant.
<samp> Specifies text as sample output from a computer program.
<script> Places script in the document for client-side processing.
<section> Defines a section of a document, such as header, footer etc.
<select> Defines a selection list within a form.
<small> Displays text in a smaller size.
<source> Defines alternative media resources for the media elements like <audio> or <video>.
<span> Defines an inline styleless section in a document.
<strike> Obsolete Displays text in strikethrough style.
<strong> Indicate strongly emphasized text.
<style> Inserts style information (commonly CSS) into the head of a document.
<sub> Defines subscripted text.
<summary> Defines a summary for the <details> element.
<sup> Defines superscripted text.
<svg> Embed SVG (Scalable Vector Graphics) content in an HTML document.
<table> Defines a data table.
<tbody> Groups a set of rows defining the main body of the table data.
<td> Defines a cell in a table.
<template> Defines the fragments of HTML that should be hidden when the page is loaded, but can be cloned a
Tag Description
inserted in the document by JavaScript.
<textarea> Defines a multi-line text input control (text area).
<tfoot> Groups a set of rows summarizing the columns of the table.
<th> Defines a header cell in a table.
<thead> Groups a set of rows that describes the column labels of a table.
<time> Represents a time and/or date.
<title> Defines a title for the document.
<tr> Defines a row of cells in a table.
<track> Defines text tracks for the media elements like <audio> or <video>.
<tt> Obsolete Displays text in a teletype style.
<u> Displays text with an underline.
<ul> Defines an unordered list.
<var> Defines a variable.
<video> Embeds video content in an HTML document.
<wbr> Represents a line break opportunity.

Lesson# 148 – HTML5 Semantics


Learning objectives

After completing this topic, a student will be able to:

 Describe about Semantics Elements


 Describe about New Sematic Elements in HTML5

Semantics (computer science)


In programming language theory, semantics is the field concerned with the rigorous mathematical study
of the meaning of programming languages. It does so by evaluating the meaning of syntactically valid
strings defined by a specific programming language, showing the computation involved. In such a case
that the evaluation would be of syntactically invalid strings, the result would be non-computation.
Semantics describes the processes a computer follows when executing a program in that specific
language. This can be shown by describing the relationship between the input and output of a program,
or an explanation of how the program will be executed on a certain platform, hence creating a model of
computation.

Lesson# 149 – HTML5 Semantics


Learning objectives

After completing this topic, a student will be able to:


 Describe about HTML5 <section> Element
 Describe about HTML5 <article> Element
 Describe about HTML5 <header> Element
 Describe about HTML5 <footer> Element
 Describe about HTML5 <nav> Element
 Describe about HTML5 <aside> Element
 Describe about HTML5 <figure> and <figcaption> Element
 Why Semantic HTML5 Elements

Approaches
There are many approaches to formal semantics; these belong to three major classes:

 Denotational semantics, whereby each phrase in the language is interpreted as a denotation, i.e.
a conceptual meaning that can be thought of abstractly. Such denotations are often
mathematical objects inhabiting a mathematical space, but it is not a requirement that they
should be so. As a practical necessity, denotations are described using some form of
mathematical notation, which can in turn be formalized as a denotational metalanguage. For
example, denotational semantics of functional languages often translate the language into
domain theory. Denotational semantic descriptions can also serve as compositional translations
from a programming language into the denotational metalanguage and used as a basis for
designing compilers.
 Operational semantics, whereby the execution of the language is described directly (rather than
by translation). Operational semantics loosely corresponds to interpretation, although again the
"implementation language" of the interpreter is generally a mathematical formalism.
Operational semantics may define an abstract machine (such as the SECD machine), and give
meaning to phrases by describing the transitions they induce on states of the machine.
Alternatively, as with the pure lambda calculus, operational semantics can be defined via
syntactic transformations on phrases of the language itself;
 Axiomatic semantics, whereby one gives meaning to phrases by describing the axioms that apply
to them. Axiomatic semantics makes no distinction between a phrase's meaning and the logical
formulas that describe it; its meaning is exactly what can be proven about it in some logic. The
canonical example of axiomatic semantics is Hoare logic.

Apart from the choice between denotational, operational, or axiomatic approaches, most variations in
formal semantic systems arise from the choice of supporting mathematical formalism.

Tips For Semantically Structured Content


If we want to create a well-structured document outline we need to pay attention to the following
rules:

1. The outermost sectioning element is always the <body></body> tag.

2. Sections in HTML5 can be nested.


3. Each section has its own heading hierarchy. Each of them (even the innermost nested section) can
have an h1 tag.

4. While the document outline is primarily defined by the 5 sectioning elements, it also needs proper
headings for each section.

5. It’s always the first heading element (let it be h1 or a lower rank heading tag) that defines the
heading of the given section. The following heading tags inside the same section need to be relative to
this. (If the first heading is an h4 inside a sectioning element, don’t put an h4 after that.)

6. The sections defined by the <nav></nav>, and the <aside></aside> tags don’t belong to the main
outline of the HTML document, they are usually not rendered initially by assistive technologies.

7. Each section (body, section, article, aside, nav) can have their own <header></header> and
<footer></footer> tags, that defines the header (such as logo, author’s name, dates, meta info, etc.)
and the footer (copyright, notes, links, etc.) of that section.

Example: A Semantic Outline

Let’s see an example for a semantic document outline to see clearer how it works. Our example code
will result in the following document structure:

And here is the code with proper semantic sectioning:

<body>

<header>

<h1>Welcome On Our Website!</h1>

<p>Here is our logo and slogan.</p>

</header>

<nav>

<header>

<h2>Choose Your Interest</h2>

</header>
<ul>

<li>Menu 1</li>

<li>Menu 2</li>

<li>Menu 3</li>

</ul>

</nav>

<article>

<header>

<h1>Title of Article</h1>

<h2>Subtitle of Article</h2>

</header>

<section>

<h4>First Logical Part (e.g. "Theory")</h4>

<p>Paragraph 1 in first section</p>

<h5>Some Other Subheading in First Section</h5>

<p>Paragraph 2 in first section</p>

</section>

<section>

<h4>Second Logical Part (e.g. "Practice")</h4>

<p>Paragraph 1 in second section</p>


<p>Paragraph 2 in second section</p>

</section>

<footer>

<h5>Author Bio</h5>

<p>Paragraph in Article's Footer</p>

</footer>

</article>

<aside>

<h2>Get To Know Us Better</h2>

<section>

<h4>Popular Posts</h4>

<ul>...</ul>

</section>

<section>

<h4>Partners</h4>

<ul>...</ul>

</section>

<section>
<h4>Testimonials</h4>

<ul>...</ul>

</section>

</aside>

<footer>

<ul>

<li>Copyright</li>

<li>Social Media Links</li>

</ul>

</footer>

</body>

Lesson # 150 – HTML4 to HTML5 Migration


Learning objectives

After completing this topic, a student will be able to:

 Convert an HTML4 document to HTML5


 Different tags of HTML5
 Difference in CCS styling between HTML4 and HTML5

What is a Semantic Element?


Semantic HTML or semantic markup is HTML that introduces meaning to the web page rather
than just presentation.

For example, a “<p> </p>” tag indicates that the enclosed text is a paragraph. This is both
semantic and presentational because people know what paragraphs are, and browsers know
how to display them.

Which HTML Tags Are Semantic?

Tag Meaning
<abbr> Abbreviation
<acronym> Acronym
<blockquote> Long quotation
<dfn> Definition
<address> Address for author(s) of the document
<cite> Citation
<code> Code reference
<tt> Teletype text
<div> Logical division
<span> Generic inline style container
<del> Deleted text
<ins> Inserted text
<em> Emphasis
<strong> Strong emphasis
<h1> First-level headline
<h2> Second-level headline
<h3> Third-level headline
<h4> Fourth-level headline
<h5> Fifth-level headline
<h6> Sixth-level headline
<hr> Thematic break
<kbd> Text to be entered by the user
<pre> Pre-formatted text
<q> Short inline quotation
<samp> Sample output
<sub> Subscript
<sup> Superscript
<var> Variable or user defined text

Lesson # 151 – HTML5 Coding Conventions - a


Learning objectives

After completing this topic, a student will be able to:

 Write HTML5 code more cleanly


 Able to add images through HTML5
What is XHTML?
Extensible HyperText Markup Language (XHTML) is part of the family of XML markup languages.
It mirrors or extends versions of the widely used HyperText Markup Language (HTML).

Background of XHTML.
XHTML was developed by World Wide Web Consortium (W3C) to help web developers make
the transition from HTML to XML. By migrating to XHTML today, web developers can enter the
XML world with all of its benefits, while still remaining confident in the backward and future
compatibility of the content.

Difference between Inline vs. Block Image


Intuitively, an image seems like a block element. It has a defined width and height, and cannot be
broken over multiple lines. It behaves like a block.

Unfortunately, because of historical reasons, the HTML specification (and all browsers, by default) treat
the <img> tag as if it is an inline element. Because of the way browsers handle white space, this can
cause problems if you are not careful.

This combination of text and image looks bad on most browsers.

There at least two easy ways to fix this. The simplest is to simply make sure there is a line break
before and after your images. This is fine if you don’t care much about flowing text around your
image.

A better, more systematic way of handling the inline image problem is to images into block
elements with CSS.

img {
display: block;
}
<!-- Image is block level. No need for line breaks. -->
This is some text that appears above the image.
<img src="/wp-content/uploads/flamingo.jpg">
Using the display: block; CSS rule is a good default way of presenting images, which you can then
build upon for other types of presentation — such as wrapping text around an image within the
flow of an article.

Lesson # 153 – HTML5 Canvas


Learning objectives

After completing this topic, a student will be able to:

 How to use HTML5 Canvas

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":

Example
document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript Can Change HTML Attribute Values


In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example

document.getElementById("demo").style.fontSize = "35px";

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

Example

document.getElementById("demo").style.display = "none";

JavaScript Can Show HTML Elements


Showing hidden HTML elements can also be done by changing the display style:

Example

document.getElementById("demo").style.display = "block";

More Features of HTML Canvas

HTML Canvas Can Draw Text


Canvas can draw colorful text, with or without animation.

HTML Canvas Can Draw Graphics


Canvas has great features for graphical data presentation with an imagery of graphs and charts.

HTML Canvas Can be Animated


Canvas objects can move. Everything is possible: from simple bouncing balls to complex animations.

HTML Canvas Can be Interactive


Canvas can respond to JavaScript events.

Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).

HTML Canvas Can be Used in Games


Canvas' methods for animations, offer a lot of possibilities for HTML gaming applications

Lesson # 154 – HTML5 Canvas Coordinates


Learning objectives

After completing this topic, a student will be able to:

 How to use HTML5 Canvas


What is HTML Canvas?
The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).

The <canvas> element is only a container for graphics. You must use a script to actually draw the
graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

HTML Canvas Can Draw Text

Canvas can draw colorful text, with or without animation.

HTML Canvas Can Draw Graphics

Canvas has great features for graphical data presentation with an imagery of graphs and charts.

Canvas Example
In HTML, a <canvas> element looks like this:

<canvas id="myCanvas" width="200" height="100"></canvas>

Line Properties
There are several properties which allow us to style lines.

S.No. Property and Description


lineWidth [ = value ]
1
This property returns the current line width and can be set, to change the line width.
lineCap [ = value ]
2
This property returns the current line cap style and can be set, to change the line
cap style. The possible line cap styles are butt, round, and square
lineJoin [ = value ]
3
This property returns the current line join style and can be set, to change the line join
style. The possible line join styles are bevel, round, andmiter.
4 miterLimit [ = value ]

This property returns the current miter limit ratio and can be set, to change the miter
limit ratio.
Example
Following is a simple example which makes use of lineWidth property to draw lines of
different width.

<!DOCTYPE HTML>

<html>

<head>

<style>

#test {

width: 100px;

height:100px;

margin: 0px auto;

</style>

<script type = "text/javascript">

function drawShape() {

// get the canvas element using the DOM

var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing

var ctx = canvas.getContext('2d');

for (i=0;i<10;i++){

ctx.lineWidth = 1+i;

ctx.beginPath();

ctx.moveTo(5+i*14,5);

ctx.lineTo(5+i*14,140);

ctx.stroke();

} else {

alert('You need Safari or Firefox 1.5+ to see this


demo.');

</script>

</head>

<body id = "test" onload = "drawShape();">

<canvas id = "mycanvas"></canvas>

</body>

</html>
The above example would draw following shape –

Lesson # 155 – HTML5 Canvas Text


Learning objectives

After completing this topic, a student will be able to:

 To draw text on Canvas

How to render context on Canvas?


The <canvas> is initially blank, and to display something, a script first needs to access
the rendering context and draw on it.

The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter, the
type of context “2d” i.e. Two Dimensional.

Following is the code to get required context along with a check if your browser
supports <canvas> element −

var canvas = document.getElementById("mycanvas");

if (canvas.getContext) {

var ctx = canvas.getContext('2d');

// drawing code here

} else {

// canvas-unsupported code here

Adding Color and Center Text


Example

Set font to 30px "Comic Sans MS" and write a filled red text in the center of the canvas:

Code:

var canvas = document.getElementById("myCanvas");


var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2,
canvas.height/2);

Lesson # 156 – HTML 5 Canvas Images


Learning objectives

After completing this topic, a student will be able to:

 Use SVG images in Canvas

Using images in Canvas


Until now we have created our own shapes and applied styles to them. One of the more exciting
features of <canvas> is the ability to use images. These can be used to do dynamic photo
compositing or as backdrops of graphs, for sprites in games, and so forth.

External images can be used in any format supported by the browser, such as PNG, GIF, or
JPEG. You can even use the image produced by other canvas elements on the same page as the
source!

Importing images into a canvas is basically a two-step process:

1. Get a reference to an HTMLImageElement object or to another canvas element as a source. It is


also possible to use images by providing a URL.
2. Draw the image on the canvas using the drawImage() function.
Getting images to draw
The canvas API is able to use any of the following data types as an image source:

 HTMLImageElement

These are images created using the Image() constructor, as well as


any <img> element.

 SVGImageElement

These are images embedded using the <image> element.

 HTMLCanvasElement

You can use another <canvas> element as your image source.

Available Methods for Canvas Image


Following are some methods which can be applied on image exported on canvas.

Sr.No. Method and Description

beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3
This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)

6 This method draws the given image onto the canvas. Here image is a reference
to an image or canvas object. x and y form the coordinate on the target canvas
where our image should be placed.
Example
Following is a simple example which makes use of above mentioned methods to import
an image.

<!DOCTYPE HTML>

<html>

<head>

<script type = "text/javascript">

function drawShape() {

// get the canvas element using the DOM

var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported

if (canvas.getContext) {

// use getContext to use the canvas for drawing

var ctx = canvas.getContext('2d');

// Draw shapes

var img = new Image();

img.src = '/images/backdrop.jpg';
img.onload = function() {

ctx.drawImage(img,0,0);

ctx.beginPath();

ctx.moveTo(30,96);

ctx.lineTo(70,66);

ctx.lineTo(103,76);

ctx.lineTo(170,15);

ctx.stroke();

} else {

alert('You need Safari or Firefox 1.5+ to see this


demo.');

</script>

</head>

<body onload = "drawShape();">

<canvas id = "mycanvas"></canvas>

</body>
</html>

It will produce the following result –

Lesson # 157 – HTML5 SVG and Canvas


Learning objectives

After completing this topic, a student will be able to:

 Distinguish between SVG and Canvas

Differences Between SVG and Canvas


SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG
DOM. You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG


object are changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is


forgotten by the browser. If its position should be changed, the entire scene
needs to be redrawn, including any objects that might have been covered by the
graphic.

Comparison of Canvas and SVG


The table below shows some important differences between Canvas and SVG:

Canvas SVG

 Resolution dependent  Resolution independent


 No support for event  Support for event handlers
handlers  Best suited for applications with large
 Poor text rendering rendering areas (Google Maps)
capabilities  Slow rendering if complex (anything
 You can save the resulting that uses the DOM a lot will be slow)
image as .png or .jpg  Not suited for game applications
 Well suited for graphic-
intensive games

Lesson # 158 – HTML5 Multimedia


Learning objectives

After completing this topic, a student will be able to:

 Add multimedia to webpage using HTML5

HTML5 and Media


HTML5 was first released in a public-facing form on 22 January 2008, with a major update and "W3C
Recommendation" status in October 2014. Its goals were to improve the language with support for the
latest multimedia and other new features; to keep the language both easily readable by humans and
consistently understood by computers and devices such as web browsers, parsers, etc., without
XHTML's rigidity; and to remain backward-compatible with older software. HTML5 is intended to
subsume not only HTML 4 but also XHTML 1 and DOM Level 2 HTML.

HTML5 includes detailed processing models to encourage more interoperable implementations; it


extends, improves, and rationalizes the markup available for documents and introduces markup and
application programming interfaces (APIs) for complex web applications. For the same reasons, HTML5
is also a candidate for cross-platform mobile applications because it includes features designed with
low-powered devices in mind.

Many new syntactic features are included. To natively include and handle multimedia and graphical
content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector
graphics (SVG) content and MathML for mathematical formulas was also added.

The first factor in HTML vs HTML5 is the introduction of audio and video in HTML5. There was no such
concept of media in case of HTML. But it is one of the integral part of the 5th Version.

Lesson # 159 – HTML5 Video


Learning objectives

After completing this topic, a student will be able to:


 Include videos in a webpage

HTML5 and Media


HTML5 was first released in a public-facing form on 22 January 2008, with a major update and "W3C
Recommendation" status in October 2014. Its goals were to improve the language with support for the
latest multimedia and other new features; to keep the language both easily readable by humans and
consistently understood by computers and devices such as web browsers, parsers, etc., without
XHTML's rigidity; and to remain backward-compatible with older software. HTML5 is intended to
subsume not only HTML 4 but also XHTML 1 and DOM Level 2 HTML.

HTML5 includes detailed processing models to encourage more interoperable implementations; it


extends, improves, and rationalizes the markup available for documents and introduces markup and
application programming interfaces (APIs) for complex web applications. For the same reasons, HTML5
is also a candidate for cross-platform mobile applications because it includes features designed with
low-powered devices in mind.

Many new syntactic features are included. To natively include and handle multimedia and graphical
content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector
graphics (SVG) content and MathML for mathematical formulas was also added.

The first factor in HTML vs HTML5 is the introduction of audio and video in HTML5. There was no such
concept of media in case of HTML. But it is one of the integral part of the 5th Version.

HTML <video> Autoplay and muted attribute


Add muted after autoplay to let your video start playing automatically (but muted):

Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

Lesson # 160 – CSS3 Multi-Column Layout


Learning objectives

After completing this topic, a student will be able to:

 Use multi-column layout through CSS


What is CSS?
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It
allows one to adapt the presentation to different types of devices, such as large screens, small screens,
or printers. CSS is independent of HTML and can be used with any XML-based markup language. The
separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and
tailor pages to different environments. This is referred to as the separation of structure (or: content)
from presentation.

Why we Use CSS?

CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.

Lesson # 161 – HTML5 Plug-ins


Learning objectives

After completing this topic, a student will be able to:

 Use HTML5 Helpers and Plug-ins

Benefits of using HTML5 Plugins

 Plug-ins are mainly used to extend the functionality of the Html browser.

 Using html, you can add or show your YouTube video on web page.
 Steps to add video on web page.
 Upload video on YouTube.
 get video id.
 Define an <iframe> element in your web page.
 Specify height and width of iframe for display video.

Lesson # 162 – HTML5 Geo Location


Learning objectives

After completing this topic, a student will be able to:

 Locate the User's Position

What are APIs?


Application Programming Interfaces (APIs) are constructs made available in programming
languages to allow developers to create complex functionality more easily. They abstract more
complex code away from you, providing some easier syntax to use in its place.

As a real-world example, think about the electricity supply in your house, apartment, or other
dwellings. If you want to use an appliance in your house, you plug it into a plug socket and it
works. You don't try to wire it directly into the power supply — to do so would be really
inefficient and, if you are not an electrician, difficult and dangerous to attempt.

A Web API is a developer's dream.

 It can extend the functionality of the browser


 It can greatly simplify complex functions
 It can provide easy syntax to complex code

Lesson # 163 – HTML5 Drag/Drop


Learning objectives

After completing this topic, a student will be able to:

 Add draggable HTML5 elements

How can we drag an image back and forth


How to drag (and drop) an image back and forth between two <div> elements:

function allowDrop(ev) {

ev.preventDefault();

function drag(ev) {

ev.dataTransfer.setData("text", ev.target.id);

function drop(ev) {

ev.preventDefault();

var data = ev.dataTransfer.getData("text");


ev.target.appendChild(document.getElementById(data));

Lesson # 164 – HTML5 Local Storage


Learning objectives

After completing this topic, a student will be able to:

 Use HTML local storage

Local Storage VS Cookies


On client and server, the following storages are available: local storage, session storage, and cookies.

The Local Storage is designed for storage that spans multiple windows and lasts beyond the current
session. In particular, Web applications may wish to store megabytes of user data, such as entire user-
authored documents or a user's mailbox, on the client side for performance reasons. Cookies do not
handle this case well because they are transmitted with every request.

Local Storage is available for every page and remains even when the web browser is closed, but you
cannot read it on the server.

The stored data has no expiration date in local storage. With cookies, you can set the expiration
duration.

If you want to clear local storage, then do it by clearing the browser cache. You can also use JavaScript
for this. Local Storage is for client side, whereas cookies are for the client as well as server side

Lesson # 165 – HTML5 App Cache


Learning objectives

After completing this topic, a student will be able to implement cache in web pages

 Cache Manifest Basics


 The Manifest File
 CACHE MANIFEST
 NETWORK and FALLBACK

What is Web Storage?


The HTML5's web storage feature lets you store some information locally on the user's computer,
similar to cookies, but it is faster and much better than cookies. However, web storage is no more
secure than cookies. Please check out the tutorial on PHP cookies to learn more about cookies.

The information stored in the web storage isn't sent to the web server as opposed to the cookies where
data sent to the server with every request. Also, where cookies let you store a small amount of data
(nearly 4KB), the web storage allows you to store up to 5MB of data.

There are two types of web storage, which differ in scope and lifetime:

Local storage — The local storage uses the local Storage object to store data for your entire website on
a permanent basis. That means the stored local data will be available on the next day, the next week, or
the next year unless you remove it.

Session storage — The session storage uses the session Storage object to store data on a temporary
basis, for a single browser window or tab. The data disappears when session ends i.e., when the user
closes that browser window or tab.

Advantages of Caching
Webpages can be cached pre-fetched on the clients, the proxies, and the servers. There are many
advantages of web caching, including an improved performance of the web.

Caching reduces bandwidth consumption; therefore, it decreases network traffic and diminishes
network congestion

Caching reduces access latency for two reasons:

 Frequently accessed documents are fetched from a nearby proxy cache instead of remote data
servers; therefore, the transmission delay is minimized.
 b) Caching can reduce the network traffic, so those documents that are not cached can also be
retrieved comparatively faster than without caching due to less congestion along the path and
with less work load on the server.
 Caching reduces the workload of the remote web server by spreading the data widely among
the proxy caches over the WAN.
 In a scenario where the remote server is not available due to a crash or network partitioning,
the client can obtain a cached copy at the proxy. Hence, the robustness of the Web service is
enhanced.

Lesson # 166 – HTML5 Web Workers


Learning objectives

After completing this topic, a student will be able to implement cache in web page

 the usage of HTML web workers


What Is a Thread?
All programmers are familiar with writing sequential programs. You’ve probably
written a program that displays "Hello World!" or sorts a list of names or computes a
list of prime numbers. These are sequential programs. That is, each has a beginning,
an execution sequence, and an end. At any given time during the runtime of the
program, there is a single point of execution.

A thread is similar to the sequential programs described previously. A single thread


also has a beginning, a sequence, and an end. At any given time during the runtime
of the thread, there is a single point of execution. However, a thread itself is not a
program; a thread cannot run on its own. Rather, it runs within a program. The
following figure shows this relationship.

A Web browser is an example of a multithreaded application. Within a typical


browser, you can scroll a page while it’s downloading an applet or an image, play
animation and sound concurrently, print a page in the background while you
download a new page, or watch three sorting algorithms race to the finish.

Some texts call a thread a lightweight process. A thread is similar to a real process in
that both have a single sequential flow of control. However, a thread is considered
lightweight because it runs within the context of a full-blown program and takes
advantage of the resources allocated for that program and the program’s
environment.

As a sequential flow of control, a thread must carve out some of its own resources
within a running program. For example, a thread must have its own execution stack
and program counter. The code running within the thread works only within that
context. Some other texts use execution context as a synonym for thread.

Lesson # 167 – HTML5 SSE


Learning objectives

After completing this topic, a student will be able to implement cache in web pages

 learn about Server Sent Events

PHP Introduction:
Because we will learn about some server code written in PHP in the lessen let’s look at php basics:

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>

PHP Variables Example:

<!DOCTYPE html><html><body>

<?php

$txt = "Hello world!";

$x = 5;

$y = 10.5;

echo $txt;

echo "<br>";

echo $x;

echo "<br>";

echo $y;

?></body></html>

SSE vs WebSockets
Similarities
I’m certain you’ve noticed certain similarities in the explanation of the two technologies thus far. If you
have, you’re not wrong — they both share the same functionality as you will see in detail now.

Apart from the fact that these two technologies operate through HTTP connections, the most noticeable
similarity is that they function exactly the same way. They both push data from the server to client, a
process also known as server push.

Differences
Obviously, the major difference between WebSockets and Server-Sent Events is that WebSockets are
bidirectional (allowing communication between the client and the server) while SSEs are mono-
directional (only allowing the client to receive data from the server).

As a result, if you are only interested in implementing server push functionalities in your application,
they are both good choices to consider. However, if you’re more interested in a bi-directional
communication system, WebSockets will serve your needs better.

Lesson# – 168 HTML5 Case Study


Learning objectives

After completing this topic, a student will be able to:

 Draw moveable objects using HTML5 Canvas

What is HTML5 Canvas?


HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can
be used to draw graphs, make photo compositions or do simple (and not so simple) animations.

The Rendering Context


The <canvas> is initially blank, and to display something, a script first needs to access the rendering
context and draw on it. The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter, the type of context2d.

Following is the code to get required context along with a check if your browser supports <canvas>
element −
var canvas = document.getElementById("mycanvas");

if (canvas.getContext) {

var ctx = canvas.getContext('2d');

// drawing code here

} else {

// canvas-unsupported code here

How to draw circle using HTML5 canvas.

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>

What is HTML5 Canvas - Animations


HTML5 canvas provides necessary methods to draw an image and erase it completely. We can take
JavaScript help to simulate good animation over a HTML5 canvas.

Following are the two important JavaScript methods which would be used to animate an image on a
canvas −

Sr.No. Method and Description


1 setInterval(callback, time);
This method repeatedly executes the supplied code after a given timemilliseconds.
setTimeout(callback, time);
2
This method executes the supplied code only once after a given time millisecond

Lesson# – 169 CSS3 Introduction


Learning objectives

After completing this topic, a student will be able to:

 Understand CSS3 modules

What You Can Do with CSS?


There are lot more things you can do with CSS.

 You can easily apply same style rules on multiple elements.


 You can control the presentation of multiple pages of a website with a single style sheet.
 You can present the same page differently on different devices.
 You can style dynamic states of elements such as hover, focus, etc. that isn't possible
otherwise.
 You can change the position of an element on a web page without changing the markup.
 You can alter the display of existing HTML elements.
 You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
 You can create animations and transitions effects without using any JavaScript.
 You can create print friendly version of your web pages.

The list does not end here, there are many other interesting things that you can do with CSS.

Advantages of Using CSS


The biggest advantage of CSS is that it allows the separation of style and layout from the
content of the document. Here are some more advantages, why one should start using CSS?

 CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups
of HTML elements, and can also be reused in multiple HTML pages.
 Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
 Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
 Superior Styles to HTML — CSS has much wider presentation capabilities than HTML
and provide much better control over the layout of your web pages. So, you can give far
better look to your web pages in comparison to the HTML presentational elements and
attributes.
 Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS, the same HTML document can be
presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc.

What is Selector?
A CSS selector is a pattern to match the elements on a web page. The style rules associated with
that selector will be applied to the elements that match the selector pattern.

Selectors are one of the most important aspects of CSS as they allow you to target specific
elements on your web page in various ways so that they can be styled.

Several types of selectors are available in CSS, let's take a closer look at them:

Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page.
The universal selector may be omitted if other conditions exist on the element. This selector is
often used to remove the default margins and paddings from the elements for quick testing
purpose.

Lesson# 170- SS3 Round Corners


Learning objectives

After completing this topic, a student will be able to :

 We will learn more about CSS3 borders and making rounded corners using border-radius

What is CSS?
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It
allows one to adapt the presentation to different types of devices, such as large screens, small screens,
or printers. CSS is independent of HTML and can be used with any XML-based markup language. The
separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and
tailor pages to different environments. This is referred to as the separation of structure (or: content)
from presentation.

Why we Use CSS?

CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.

1.
1. CSS Borders

The CSS border properties allow you to specify the style, width, and color of an element's border.

1.
2. CSS Border Style

The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border, bottom
border, and the left border).

You shall not have to worry if you are unfamiliar with the terms discussed in video. You will be able to
explore more as we dig deeper into the components of this course.

CSS border Property


The border property is a shorthand property for:

 border-width
 border-style (required)
 border-color
If border-color is omitted, the color applied will be the color of the text.

The border property may be specified using one, two, or three of the values listed below. The
order of the values does not matter.

Values

<line-width>

Sets the thickness of the border. Defaults to medium if absent. See border-width.

<line-style>

Sets the style of the border. Defaults to none if absent. See border-style.

<color>

Sets the color of the border. Defaults to currentcolor if absent. See border-color.

Lesson# 171 – CSS3 Border Image


Learning objectives

After completing this topic, a student will be able to :

 How to use imges in borders using CSS3

CSS Border Image Properties


The only required property for the border-image shorthand is border-image-source. The other
properties default to their initial values if they’re not specified. These are the border-image properties in
order:

 border-image-source
 border-image-slice
 border-image-width

Lesson# 172 – CSS3 Backgrounds-a


Learning objectives

After completing this topic, a student will be able to:


 Basics of CSS3 Backgrounds

CSS background properties


CSS background is made up of eight other properties:

• background-image
• background-position
• background-size
• background-repeat
• background-attachment
• background-origin
• background-clip
• background-color
You can use any combination of these properties that you like, in almost any order
(although the order recommended in the spec is above). There is a gotcha though:
anything you don’t specify in the background property is automatically set to its
default.

Lesson# 174 -CSS3 Colors


Learning objectives

After completing this topic, a student will be able to:

 To learn the use of different color types and properties in CSS3.

CSS Color Names


In CSS, a color can be specified by using a predefined color name e.g., Gray, Light
Gray and Orange.

Color Names Supported by All Browsers


140 colors Names of CSS are supported by all the modern browsers.

Lesson# 174 -CSS3 Colors


Learning objectives

After completing this topic, a student will be able to:

 To learn the use of different color types and properties in CSS3.

CSS Color Names


In CSS, a color can be specified by using a predefined color name e.g., Gray, Light
Gray and Orange.

Color Names Supported by All Browsers


140 colors Names of CSS are supported by all the modern browsers.

Lesson# 177 - CSS3 Shadow Effects


Learning objectives

After completing this topic, a student will be able to:

 To learn about text and box shadows in CSS3

Cards
You can also use the box-shadow property to create paper-like cards:

Code Example:

div.card {
width: 250px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
text-align: center;
}

Lesson# 178 -CSS3 Text Effects and Fonts


Learning objectives

After completing this topic, a student will be able to:


 Features of CSS3 for Text Effects

CSS Borders

The CSS border properties allow you to specify the style, width, and color of an element's border.

CSS Text

CSS has a lot of properties for formatting text.

Text Color

The color property is used to set the color of the text. The color is specified by:

a color name - like "red"

a HEX value - like "#ff0000"

an RGB value - like "rgb(255,0,0)"

Look at CSS Color Values for a complete list of possible color values.

The default text color for a page is defined in the body selector.

Text Color and Background Color

We Can define both the background-color property and the color property to body:

body {
background-color: lightgrey;
color: blue;
}

CSS Writing Mode


The CSS writing-mode property specifies whether lines of text are laid out horizontally or vertically.

CSS Text Effect Properties


text-align-last: Specifies how justified text should be aligned and spaced

text-justify: Specifies how overflowed content that is not displayed should be signaled to the user
text-overflow: Specifies line breaking rules for non-CJK scripts

word-break: Allows long words to be able to be broken and wrap onto the next line

word-wrap: Specifies whether lines of text are laid out horizontally or vertically

Lesson# 180 -CSS3 Transitions


Learning objectives

 To learn about CSS3 Transitions

Transition + Transformation
In CSS3 we can combine Transition with Transforms, as we have studied Transforms earlier let’s
take an example of this concepts.

The following example adds a transition effect to the transformation:

div {
transition: width 2s, height 2s, transform 2s;
}

Lesson# 181 - CSS3 Animations


Learning objectives

 To learn about CSS3 Animations

The @keyframes Rule


When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the
current style to the new style at certain times. To get an animation to work, you must bind the
animation to an element. The following example binds the "example" animation to the <div> element.
The animation will last for 4 seconds, and it will gradually change the background-color of the <div>
element from "red" to "yellow":

/* The animation code */


@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}

/* The element to apply the animation to */


div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}

Specify the fill-mode For an Animation


CSS animations do not affect an element before the first keyframe is played or after the last
keyframe is played. The animation-fill-mode property can override this behavior.

The animation-fill-mode property specifies a style for the target element when the animation is not
playing (before it starts, after it ends, or both).

The animation-fill-mode property can have the following values:

 none - Default value. Animation will not apply any styles to the element before or after it is
executing
 forwards - The element will retain the style values that is set by the last keyframe (depends
on animation-direction and animation-iteration-count)
 backwards - The element will get the style values that is set by the first keyframe (depends on
animation-direction), and retain this during the animation-delay period
 both - The animation will follow the rules for both forwards and backwards, extending the
animation properties in both directions

The following example lets the <div> element retain the style values from the last keyframe when
the animation ends:

div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-fill-mode: forwards;
}

Lesson# 182 - Responsive Design Testing


Learning objectives
 We will learn about testing of responsive web pages.

HTML Responsive Web Design


Responsive web design is about creating web pages that look good on all devices!

A responsive web design will automatically adjust for different screen sizes and viewports.

Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a
website, to make it look good on all devices (desktops, tablets, and phones).

Lesson# 183 - CSS3-Parallax Background


Implementation
Learning objectives

 To learn about Parallax Effect of CSS3

How to Create a Parallax Scrolling Effect?


Use a container element and add a background image to the container with a specific height. Then
use the background-attachment: fixed to create the actual parallax effect. The other background
properties are used to center and scale the image perfectly:

Example with pixels


<style>
.parallax {
/* The image used */
background-image: url("img_parallax.jpg");

/* Set a specific height */


min-height: 500px;

/* Create the parallax scrolling effect */


background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
<!-- Container element -->
<div class="parallax"></div>

Lesson# 184 - Responsive Web Design (RWD)


Introduction
Learning objectives

 To learn about Responsive Web Design

HTML Responsive Web Design


Responsive web design is about creating web pages that look good on all devices!

A responsive web design will automatically adjust for different screen sizes and viewports.

Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a
website, to make it look good on all devices (desktops, tablets, and phones).

Lesson# 185 - Responsive Web Design (RWD) - The


Viewport
Learning objectives

 To learn about Viewport while making responsive web pages

Setting the Viewport?


To create a responsive website, add the following <meta> tag to all your web pages:
Example

<meta name="viewport" content="width=device-width, initial-scale=1.0">

This will set the viewport of your page, which will give the browser instructions on how to control
the page's dimensions and scaling.

Here is an example of a web page without the viewport meta tag, and the same web page with the
viewport meta tag:
Lesson# 186 - Responsive Web Design (RWD) Grid-View
Learning objectives

 To learn about Responsive Web Design (RWD) Grid-View

What is a 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 and
expand as you resize the browser window.

Lesson# 187 -Responsive Web Design (RWD) Media


Queries
Learning objectives

 To learn how to implement Media Queries

Using min- and max- to match value ranges


Many of the media features including width, height, color and color-index can be prefixed with min- or
max- to express minimum or maximum constraints.

In the following snippet, we’re painting the body’s background purple when the viewport width is wider
than 30em and narrower than 80em. If the viewport width does not match that range of values, then it
will fallback to white.

body {

background-color: #fff;

@media (min-width: 30em) and (max-width: 80em) {

body {

background-color: purple;
}

Media Queries Level 4 specifies a new and simpler syntax using less then (<), greater than (>) and equals
(=) operators.

Lesson# 188 - Responsive Web Design (RWD) Images


Learning objectives

 To learn how to make images responsive in web pages

Use modern image formats boldly


New image formats like WebP and AVIF can maintain a low file size and high quality at the same
time. These formats now have relatively broad browser support but little "historical depth".

<picture> lets us continue catering to older browsers. You can supply MIME types
inside type attributes so the browser can immediately reject unsupported file types:

<picture>

<source type="image/svg+xml" srcset="pyramid.svg">

<source type="image/webp" srcset="pyramid.webp">

<img src="pyramid.png" alt="regular pyramid built from four equilateral triangles">

</picture>

 Do not use the media attribute, unless you also need art direction.
 In a <source> element, you can only refer to images of the type declared in type.
 Use comma-separated lists with srcset and sizes, as needed.

Lesson# 189 - Responsive Web Design (RWD) Videos


Learning objectives

 To learn how can we make videos responsive in web pages

Using the width Property


If the width property is set to 100%, the video player will be responsive and scale up and down:
video {

width: 100%;

height: auto;

Here, the video player can be scaled up to be larger than its original size. A better solution, in many
cases, will be to use the max-width property instead.

If the max-width property is set to 100%, the video player will scale down if it has to, but never scale up
to be larger than its original size.

You might also like