JavaScript PDF
JavaScript PDF
com
Iauc.ac.ir
H.sohrabpoor@gmail.com
www.Sohrabpoor.com
JavaScript Tutorial
JavaScript is the programming language of HTML and the Web.
Example
My First JavaScript
Click me to display Date and Time
Try it Yourself »
<!DOCTYPE html>
<body>
</body>
</html>
We recommend reading this tutorial, in the sequence listed in the left menu.
1
www.Sohrabpoor.com
Learn by Examples
Examples are better than 1000 words. Examples are often easier to
understand than text explanations.
If you try all the examples, you will learn a lot about JavaScript, in a very
short time!
This tutorial is about JavaScript, and how JavaScript works with HTML and
CSS.
Learning Speed
In this tutorial, the learning speed is your choice.
Everything is up to you.
JavaScript References
W3Schools maintains a complete JavaScript reference, including all HTML
DOM, and browser objects.
The reference contains examples for all objects, properties, and methods,
and is continuously updated according to the latest web standards.
2
www.Sohrabpoor.com
JavaScript Introduction
This page contains some examples of what JavaScript can do.
This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
3
www.Sohrabpoor.com
Try it Yourself »
Example
document.getElementById("demo").style.fontSize = "25px";
Try it Yourself »
Example
document.getElementById("demo").style.display="none";
Try it Yourself »
4
www.Sohrabpoor.com
Example
document.getElementById("demo").style.display="block";
Try it Yourself »
JavaScript Where To
JavaScript can be placed in the <body> and the <head> sections of an
HTML page.
Example
5
www.Sohrabpoor.com
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
For example, a function can be executed when an event occurs, like when
the user clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an
HTML page.
Example
6
www.Sohrabpoor.com
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
</body>
</html>
Try it Yourself »
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an
HTML page.
Example
7
www.Sohrabpoor.com
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Try it Yourself »
External JavaScript
Scripts can also be placed in external files:
myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different
web pages.
To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
Example
8
www.Sohrabpoor.com
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Try it Yourself »
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is
located.
JavaScript Output
9
www.Sohrabpoor.com
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Try it Yourself »
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
10
www.Sohrabpoor.com
<script>
document.write(5 + 6);
</script>
</body>
</html>
Try it Yourself »
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
Example
<!DOCTYPE html>
<html>
11
www.Sohrabpoor.com
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Try it Yourself »
To "display data" in HTML, (in most cases) you will set the value of an
innerHTML property.
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Try it Yourself »
JavaScript Syntax
12
www.Sohrabpoor.com
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the
computer.
Example
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
Try it Yourself »
JavaScript Statements
JavaScript statements are composed of:
JavaScript Values
13
www.Sohrabpoor.com
The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
10.50
1001
Try it Yourself »
"John Doe"
'John Doe'
Try it Yourself »
JavaScript Variables
In a programming language, variables are used to store data values.
var x;
x = 6;
Try it Yourself »
JavaScript Operators
14
www.Sohrabpoor.com
var x = 5;
var y = 6;
Try it Yourself »
(5 + 6) * 10
Try it Yourself »
JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
5 * 10
Try it Yourself »
x * 10
Try it Yourself »
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "John" + " " + "Doe";
</script>
Try it Yourself »
15
www.Sohrabpoor.com
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
<p id="demo"></p>
<script>
var x = 5 + 6;
var y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>
Try it Yourself »
JavaScript Comments
Not all JavaScript statements are "executed".
Try it Yourself »
JavaScript Identifiers
Identifiers are names.
The rules for legal names are much the same in most programming
languages.
lastName = "Doe";
lastname = "Peterson";
Try it Yourself »
Hyphens:
Underscore:
Camel Case:
17
www.Sohrabpoor.com
Unicode covers (almost) all the characters, punctuations, and symbols in the
world.
JavaScript Statements
❮ Previous Next ❯
JavaScript Statements
18
www.Sohrabpoor.com
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
Example
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
Try it Yourself »
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
a = 5;
b = 6;
c = a + b;
Try it Yourself »
19
www.Sohrabpoor.com
a = 5; b = 6; c = a + b;
Try it Yourself »
var x = y + z;
If a JavaScript statement does not fit on one line, the best place to break it, is after an
operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself »
20
www.Sohrabpoor.com
One place you will find statements grouped together in blocks, are in JavaScript functions:
Example
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
Try it Yourself »
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
debugger Stops the execution of JavaScript, and calls (if available) the debugging
function
do ... while Executes a block of statements, and repeats the block, while a condition is
true
21
www.Sohrabpoor.com
JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).
22
www.Sohrabpoor.com
Example
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
Try it Yourself »
This example uses a single line comment at the end of each line to explain
the code:
Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Try it Yourself »
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
23
www.Sohrabpoor.com
Adding // in front of a code line changes the code lines from an executable
line to a comment.
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
Try it Yourself »
JavaScript Variables
JavaScript Variables
JavaScript variables are containers for storing data values.
Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself »
24
www.Sohrabpoor.com
Example
<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML ="The total is: " + total;
</script>
Try it Yourself »
From the example above, you can calculate the total to be 11.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
The general rules for constructing names for variables (unique identifiers)
are:
25
www.Sohrabpoor.com
This is different from algebra. The following does not make sense in algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
JavaScript can handle many types of data, but for now, just think of numbers
and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
26
www.Sohrabpoor.com
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Try it Yourself »
var carName;
After the declaration, the variable has no value. (Technically it has the value
of undefined)
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the
value "Volvo" to it.
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
27
www.Sohrabpoor.com
Start the statement with var and separate the variables by comma:
Try it Yourself »
Try it Yourself »
Value = undefined
In computer programs, variables are often declared without a value. The
value can be something that has to be calculated, or something that will be
provided later, like user input.
The variable carName will have the value undefined after the execution of
this statement:
Example
var carName;
Try it Yourself »
The variable carName will still have the value "Volvo" after the execution of
these statements:
28
www.Sohrabpoor.com
Example
var carName = "Volvo";
var carName;
Try it Yourself »
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
Example
var x = 5 + 2 + 3;
Try it Yourself »
Example
var x = "John" + " " + "Doe";
Try it Yourself »
Example
var x = "5" + 2 + 3;
Try it Yourself »
If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.
Example
var x = 2 + 3 + "5";
Try it Yourself »
29
www.Sohrabpoor.com
JavaScript Operators
Example
Assign values to variables and add them together:
Try it Yourself »
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
30
www.Sohrabpoor.com
-- Decrement
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself »
You will learn more about JavaScript operators in the next chapters.
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
31
www.Sohrabpoor.com
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
Assignment
var x = 10;
Try it Yourself »
Assignment
var x = 10;
x += 5;
Try it Yourself »
Example
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
John Doe
Try it Yourself »
32
www.Sohrabpoor.com
Example
txt1 = "What a very ";
txt1 += "nice day";
Try it Yourself »
Example
x = 5 + 5;
y = "5" + 5;
z = "Hello" + 5;
10
55
Hello5
Try it Yourself »
The rule is: If you add a number and a string, the result will be a
string!
33
www.Sohrabpoor.com
== equal to
!= not equal
? ternary operator
34
www.Sohrabpoor.com
JavaScript Arithmetic
A typical thing to do with numbers is arithmetic.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
35
www.Sohrabpoor.com
% Modulus
++ Increment
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
Example
var x = 100 + 50;
Try it Yourself »
or variables:
Example
var x = a + b;
Try it Yourself »
or expressions:
Example
var x = (100 + 50) * a;
Try it Yourself »
36
www.Sohrabpoor.com
100 + 50
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »
Subtracting
var x = 5;
var y = 2;
var z = x - y;
Try it Yourself »
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself »
Dividing
var x = 5;
var y = 2;
var z = x / y;
Try it Yourself »
37
www.Sohrabpoor.com
Modulus
var x = 5;
var y = 2;
var z = x % y;
Try it Yourself »
Incrementing
var x = 5;
x++;
var z = x;
Try it Yourself »
Decrementing
var x = 5;
x--;
var z = x;
Try it Yourself »
Operator Precedence
Operator precedence describes the order in which operations are performed
in an arithmetic expression.
Example
var x = 100 + 50 * 3;
Try it Yourself »
Is the result of example above the same as 150 * 3, or is it the same as 100
+ 150?
Multiplication (*) and division (/) have higher precedence than addition (+)
and subtraction (-).
Example
var x = (100 + 50) * 3;
Try it Yourself »
When many operations have the same precedence (like addition and
subtraction), they are computed from left to right:
Example
var x = 100 + 50 - 3;
Try it Yourself »
19 () Expression grouping (3 + 4)
18 . Member person.name
18 [] Member person["name"]
39
www.Sohrabpoor.com
14 * Multiplication 10 * 5
40
www.Sohrabpoor.com
14 / Division 10 / 5
14 % Modulo division 10 % 5
14 ** Exponentiation 10 ** 2
13 + Addition 10 + 5
13 - Subtraction 10 - 5
41
www.Sohrabpoor.com
10 == Equal x == y
10 != Unequal x != y
5 || Or x || y
3 = Assignment x=y
3 += Assignment x += y
3 -= Assignment x -= y
42
www.Sohrabpoor.com
3 *= Assignment x *= y
3 /= Assignment x /= y
Expressions in parentheses are fully computed before the value is used in the
rest of the expression.
JavaScript Assignment
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
43
www.Sohrabpoor.com
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
Assignment
var x = 10;
Try it Yourself »
Assignment
var x = 10;
x += 5;
Try it Yourself »
Assignment
var x = 10;
x -= 5;
Try it Yourself »
Assignment
var x = 10;
x *= 5;
Try it Yourself »
44
www.Sohrabpoor.com
Assignment
var x = 10;
x /= 5;
Try it Yourself »
Assignment
var x = 10;
x %= 5;
Try it Yourself »
45
www.Sohrabpoor.com
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or
will it produce a result?
When adding a number and a string, JavaScript will treat the number as a
string.
Example
var x = 16 + "Volvo";
Try it Yourself »
Example
var x = "Volvo" + 16;
Try it Yourself »
JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
Try it Yourself »
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
Try it Yourself »
46
www.Sohrabpoor.com
In the second example, since the first operand is a string, all operands are
treated as strings.
Example
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example
var answer = "It's alright"; // Single quote inside double
quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double
quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single
quotes
Try it yourself »
47
www.Sohrabpoor.com
JavaScript Numbers
JavaScript has only one type of numbers.
Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Try it yourself »
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x = true;
var y = false;
You will learn more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square brackets.
48
www.Sohrabpoor.com
The following code declares (creates) an array called cars, containing three
items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Array indexes are zero-based, which means the first item is [0], second is
[1], and so on.
JavaScript Objects
JavaScript objects are written with curly braces.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Try it Yourself »
Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object" (not "array", see note
49
www.Sohrabpoor.com
below)
typeof {name:'John', age:34} // Returns "object"
Try it Yourself »
The typeof operator returns "object" for arrays because in JavaScript arrays
are objects.
Undefined
In JavaScript, a variable without a value, has the value undefined. The
typeof is also undefined.
Example
var person; // Value is undefined, type is undefined
Try it Yourself »
Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.
Example
person = undefined; // Value is undefined, type is undefined
Try it Yourself »
Empty Values
An empty value has nothing to do with undefined.
Example
var car = ""; // The value is "", the typeof is "string"
Try it Yourself »
50
www.Sohrabpoor.com
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't
exist.
You can consider it a bug in JavaScript that typeof null is an object. It should
be null.
Example
var person = null; // Value is null, but type is still an object
Try it Yourself »
Example
var person = undefined; // Value is undefined, type is undefined
Try it Yourself »
Try it Yourself »
51
www.Sohrabpoor.com
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1
and p2
}
Try it Yourself »
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
52
www.Sohrabpoor.com
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
function myFunction(a, b) {
return a * b; // Function returns the product of a and
b
}
12
Try it Yourself »
53
www.Sohrabpoor.com
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
Try it Yourself »
Example
Accessing a function without () will return the function definition:
<p id="demo"></p>
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Try it Yourself »
54
www.Sohrabpoor.com
Example
Instead of using a variable to store the return value of a function:
var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
You will learn a lot more about functions later in this tutorial.
JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and
stop:
All cars have the same properties, but the property values differ from car to
car.
55
www.Sohrabpoor.com
All cars have the same methods, but the methods are performed at different
times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data
values.
Try it Yourself »
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
Try it Yourself »
The values are written as name:value pairs (name and value separated by a
colon).
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
firstName John
56
www.Sohrabpoor.com
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
firstName John
lastName Doe
age 50
eyeColor blue
57
www.Sohrabpoor.com
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Try it Yourself »
Spaces and line breaks are not important. An object definition can span
multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Try it Yourself »
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Try it Yourself »
Example2
person["lastName"];
Try it Yourself »
58
www.Sohrabpoor.com
objectName.methodName()
Example
name = person.fullName();
Try it Yourself »
If you access the fullName method, without (), it will return the function
definition:
Example
name = person.fullName;
Try it Yourself »
Avoid String, Number, and Boolean objects. They complicate your code and
slow down execution speed.
59
www.Sohrabpoor.com
JavaScript Scope
Scope is the set of variables you have access to.
JavaScript Scope
In JavaScript, objects and functions are also variables.
Local variables have local scope: They can only be accessed within the
function.
Example
// code here can not use carName
function myFunction() {
var carName = "Volvo";
Try it Yourself »
Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
60
www.Sohrabpoor.com
A global variable has global scope: All scripts and functions on a web page
can access it.
Example
var carName = " Volvo";
function myFunction() {
Try it Yourself »
Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the value
is assigned inside a function.
Example
myFunction();
function myFunction() {
carName = "Volvo";
}
Try it Yourself »
61
www.Sohrabpoor.com
In HTML, the global scope is the window object. All global variables belong to
the window object.
Example
var carName = "Volvo";
Try it Yourself »
Function Arguments
Function arguments (parameters) work as local variables inside functions.
62
www.Sohrabpoor.com
JavaScript Events
HTML events are "things" that happen to HTML elements.
HTML Events
An HTML event can be something the browser does, or something a user
does.
Example
<button onclick='document.getElementById("demo").innerHTML=Date()'>The
time is?</button>
<p id="demo"></p>
Try it Yourself »
63
www.Sohrabpoor.com
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML=Date()">The time is?</button>
Try it Yourself »
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Try it Yourself »
Event Description
onmouseout The user moves the mouse away from an HTML element
64
www.Sohrabpoor.com
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM
chapters.
JavaScript Strings
JavaScript strings are used for storing and manipulating text.
JavaScript Strings
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
65
www.Sohrabpoor.com
Example
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
Try it Yourself »
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Try it Yourself »
String Length
The length of a string is found in the built in property length:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it Yourself »
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:
66
www.Sohrabpoor.com
Example
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
Try it Yourself »
The escape character (\) can also be used to insert other special characters
in a string.
This is the list of special characters that can be added to a text string with
the backslash sign:
Code Outputs
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
67
www.Sohrabpoor.com
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
Example
document.getElementById("demo").innerHTML ="Hello Dolly.";
Try it Yourself »
You can also break up a code line within a text string with a single
backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
Try it Yourself »
The safest (but a little slower) way to break a long string is to use string
addition:
Example
document.getElementById("demo").innerHTML = "Hello" + "Dolly!";
Try it Yourself »
Example
document.getElementById("demo").innerHTML = \"Hello Dolly!";
Try it Yourself »
68
www.Sohrabpoor.com
But strings can also be defined as objects with the keyword new: var
firstName = new String("John")
Example
var x = "John";
var y = new String("John");
Try it Yourself »
Example
var x = "John";
var y = new String("John");
Try it Yourself »
When using the === equality operator, equal strings are not equal, because
the === operator expects equality in both type and value.
Example
var x = "John";
var y = new String("John");
Try it Yourself »
69
www.Sohrabpoor.com
Example
var x = new String("John");
var y = new String("John");
Try it Yourself »
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
String Length
The length property returns the length of a string:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it Yourself »
70
www.Sohrabpoor.com
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
Try it Yourself »
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Try it Yourself »
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not
found.
Both methods accept a second parameter as the starting position for the
search.
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Try it Yourself »
71
www.Sohrabpoor.com
They accept the same arguments (parameters), and they return the same
value.
The two methods are equal, but the search() method can take much more
powerful search values.
You will learn more about powerful search values in the chapter about
regular expressions.
slice(start, end)
substring(start, end)
substr(start, length)
The method takes 2 parameters: the starting index (position), and the
ending index (position).
This example slices out a portion of a string from position 7 to position 13:
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
Banana
Try it Yourself »
72
www.Sohrabpoor.com
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
Banana
Try it Yourself »
If you omit the second parameter, the method will slice out the rest of the
string:
Example
var res = str.slice(7);
Try it Yourself »
Example
var res = str.slice(-12);
Try it Yourself »
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
document.getElementById("demo").innerHTML = str.substring(7,13);
73
www.Sohrabpoor.com
Banana
Try it Yourself »
If you omit the second parameter, substring() will slice out the rest of the
string.
The difference is that the second parameter specifies the length of the
extracted part.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);
Banana
Try it Yourself »
If the first parameter is negative, the position counts from the end of the
string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the
string.
74
www.Sohrabpoor.com
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
Try it Yourself »
The replace() method can also take a regular expression as the search value.
By default, the replace() function replaces only the first match. To replace all
matches, use a regular expression with a g flag (for global match):
Example
str = "Please visit Microsoft!";
var n = str.replace(/Microsoft/g,"W3Schools");
Try it Yourself »
The replace() method does not change the string it is called on. It returns a
new string.
Example
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
Try it Yourself »
Example
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Try it Yourself »
75
www.Sohrabpoor.com
Example
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
Try it Yourself »
The concat() method can be used instead of the plus operator. These two
lines do the same:
Example
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only
replaced.
charAt(position)
charCodeAt(position)
Example
var str = "HELLO WORLD";
str.charAt(0); // returns H
Try it Yourself »
76
www.Sohrabpoor.com
Example
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
Try it Yourself »
str[0]; // returns H
Example
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Try it Yourself »
77
www.Sohrabpoor.com
If the separator is omitted, the returned array will contain the whole string in
index [0].
If the separator is "", the returned array will be an array of single characters:
Example
var txt = "Hello"; // String
txt.split(""); // Split in characters
Try it Yourself »
The reference contains descriptions and examples of all string properties and
methods.
JavaScript Numbers
JavaScript has only one type of number.
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example
var x = 34.00; // A number with decimals
var y = 34; // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent)
notation:
78
www.Sohrabpoor.com
Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
This format stores numbers in 64 bits, where the number (the fraction) is
stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
Precision
Integers (numbers without a period or exponent notation) are considered
accurate up to 15 digits.
Example
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
Try it Yourself »
The maximum number of decimals is 17, but floating point arithmetic is not
always 100% accurate:
79
www.Sohrabpoor.com
Example
var x = 0.2 + 0.1; // x will be 0.30000000000000004
Try it yourself »
Example
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
Try it Yourself »
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded
by 0x.
Example
var x = 0xFF; // x will be 255
Try it Yourself »
But you can use the toString() method to output numbers as base 16 (hex),
base 8 (octal), or base 2 (binary).
Example
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000
Try it Yourself »
80
www.Sohrabpoor.com
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a
number outside the largest possible number.
Example
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}
Try it yourself »
Example
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity
Try it Yourself »
Example
typeof Infinity; // returns "number"
Try it Yourself »
Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)
Try it Yourself »
81
www.Sohrabpoor.com
However, if the string contains a numeric value , the result will be a number:
Example
var x = 100 / "10"; // x will be 10
Try it Yourself »
You can use the global JavaScript function isNaN() to find out if a value is a
number.
Example
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
Try it Yourself »
Watch out for NaN. If you use NaN in a mathematical operation, the result
will also be NaN:
Example
var x = NaN;
var y = 5;
var z = x + y; // z will be NaN
Try it Yourself »
Example
var x = NaN;
var y = "5";
var z = x + y; // z will be NaN5
Try it Yourself »
Example
typeof NaN; // returns "number"
Try it Yourself »
82
www.Sohrabpoor.com
But numbers can also be defined as objects with the keyword new: var y =
new Number(123)
Example
var x = 123;
var y = new Number(123);
Try it yourself »
Example
var x = 500;
var y = new Number(500);
Try it Yourself »
When using the === equality operator, equal numbers are not equal,
because the === operator expects equality in both type and value.
Example
var x = 500;
var y = new Number(500);
Try it Yourself »
83
www.Sohrabpoor.com
Example
var x = new Number(500);
var y = new Number(500);
Try it Yourself »
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
All number methods can be used on any type of numbers (literals, variables,
or expressions):
Example
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
Try it Yourself »
84
www.Sohrabpoor.com
Example
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
Try it yourself »
The parameter is optional. If you don't specify it, JavaScript will not round
the number.
Example
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
Try it yourself »
Example
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
Try it Yourself »
Example
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Try it Yourself »
These methods are not number methods, but global JavaScript methods.
86
www.Sohrabpoor.com
Global Methods
JavaScript global methods can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method Description
Example
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN
Try it Yourself »
87
www.Sohrabpoor.com
Example
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
Try it yourself »
Example
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Try it yourself »
88
www.Sohrabpoor.com
Number Properties
Property Description
Example
var x = Number.MAX_VALUE;
Try it yourself »
Example
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
Try it yourself »
89
www.Sohrabpoor.com
Example
Math.random(); // returns a random number
Try it Yourself »
Example
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Try it Yourself »
90
www.Sohrabpoor.com
Example
Math.max(0, 150, 30, 20, -8, -200); // returns 150
Try it Yourself »
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):
Example
Math.random(); // returns a random number
Try it Yourself »
Math.round()
Math.round() rounds a number to the nearest integer:
Example
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Try it Yourself »
Math.ceil()
Math.ceil() rounds a number up to the nearest integer:
Example
Math.ceil(4.4); // returns 5
Try it Yourself »
91
www.Sohrabpoor.com
Math.floor()
Math.floor() rounds a number down to the nearest integer:
Example
Math.floor(4.7); // returns 4
Try it Yourself »
Example
Math.floor(Math.random() * 11); // returns a random number between 0 and
10
Try it Yourself »
Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the
Math object:
Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Try it Yourself »
92
www.Sohrabpoor.com
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
93
www.Sohrabpoor.com
The reference contains descriptions and examples of all Math properties and
methods.
JavaScript Dates
The Date object lets you work with dates (years, months, days, hours,
minutes, seconds, and milliseconds)
94
www.Sohrabpoor.com
or as a number:
1474003153194
Displaying Dates
In this tutorial we use a script to display dates inside a <p> element with
id="demo":
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
Try it Yourself »
The script above says: assign the value of Date() to the content (innerHTML)
of the element with id="demo".
You will learn how to display a date, in a more readable format, at the
bottom of this page.
95
www.Sohrabpoor.com
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Using new Date(), creates a new date object with the current date and
time:
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Using new Date(date string), creates a new date object from the specified
date and time:
Example
<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Valid date strings (date formats) are described in the next chapter.
Using new Date(number), creates a new date object as zero time plus the
number.
Example
<script>
var d = new Date(86400000);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
96
www.Sohrabpoor.com
Using new Date(7 numbers), creates a new date object with the specified
date and time:
The 7 numbers specify the year, month, day, hour, minute, second, and
millisecond, in that order:
Example
<script>
var d = new Date(99,5,24,11,33,30,0);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Variants of the example above let us omit any of the last 4 parameters:
Example
<script>
var d = new Date(99,5,24);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Date Methods
When a Date object is created, a number of methods allow you to operate
on it.
Date methods allow you to get and set the year, month, day, hour, minute,
second, and millisecond of objects, using either local time or UTC (universal,
or GMT) time.
Displaying Dates
When you display a date object in HTML, it is automatically converted to a
string, with the toString() method.
97
www.Sohrabpoor.com
Example
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>
Try it Yourself »
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
Try it Yourself »
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>
Try it Yourself »
Date objects are static. The computer time is ticking, but date objects, once
created, are not.
98
www.Sohrabpoor.com
Time Zones
When setting a date, without specifying the time zone, JavaScript will use the
browser's time zone.
When getting a date, without specifying the time zone, the result is
converted to the browser's time zone.
Type Example
99
www.Sohrabpoor.com
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date
format:
Try it Yourself »
Try it Yourself »
Time zones will vary the result above between February 28 and March 01.
Try it Yourself »
Time zones will vary the result above between December 31 2014 and
January 01 2015.
100
www.Sohrabpoor.com
Try it Yourself »
The T in the date string, between the date and time, indicates UTC time.
Example
var d = new Date("03/25/2015");
Try it Yourself »
Example
var d = new Date("2015/03/25");
Try it Yourself »
Month is written before day in all short date and ISO date formats.
101
www.Sohrabpoor.com
Example
var d = new Date("2015-03-25");
Try it Yourself »
Example
var d = new Date("Mar 25 2015");
Try it Yourself »
Example
var d = new Date("25 Mar 2015");
Try it Yourself »
Example
var d = new Date("January 25 2015");
Try it Yourself »
Example
var d = new Date("Jan 25 2015");
Try it Yourself »
Example
var d = new Date("JANUARY, 25, 2015");
Try it Yourself »
102
www.Sohrabpoor.com
Example
var d = new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard
Time)");
Try it Yourself »
JavaScript will ignore errors both in the day name and in the time
parentheses:
Example
var d = new Date("Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo Time)");
Try it Yourself »
Time Zones
JavaScript accepts these time zones:
103
www.Sohrabpoor.com
When setting a date, without specifying the time zone, JavaScript will use the
browser's time zone.
When getting a date, without specifying the time zone, the result is
converted to the browser's time zone.
104
www.Sohrabpoor.com
Method Description
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>
Try it Yourself »
105
www.Sohrabpoor.com
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
Try it Yourself »
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>
Try it Yourself »
In JavaScript, the first day of the week (0) means "Sunday", even if some
countries in the world consider the first day of the week to be "Monday"
You can use an array of names, and getDay() to return the weekday as a
name:
Example
<script>
var d = new Date();
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>
Try it Yourself »
106
www.Sohrabpoor.com
Method Description
107
www.Sohrabpoor.com
Example
<script>
var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
If adding days, shifts the month or year, the changes are handled
automatically by the Date object.
108
www.Sohrabpoor.com
Example
<script>
var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>
Try it Yourself »
You can then use the number of milliseconds to convert it to a date object:
Example
<script>
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
Try it Yourself »
109
www.Sohrabpoor.com
Method Description
The reference contains descriptions and examples of all Date properties and
methods.
110
www.Sohrabpoor.com
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
111
www.Sohrabpoor.com
Spaces and line breaks are not important. A declaration can span multiple
lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
Try it Yourself »
Example
var cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »
The two examples above do exactly the same. There is no need to use new
Array().
For simplicity, readability and execution speed, use the first one (the array
literal method).
cars[0] = "Opel";
112
www.Sohrabpoor.com
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Try it Yourself »
[0] is the first element in an array. [1] is the second. Array indexes start
with 0.
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Try it Yourself »
Array:
var person = ["John", "Doe", 46];
Try it Yourself »
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself »
113
www.Sohrabpoor.com
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You
can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Examples
var x = cars.length; // The length property returns the number of
elements
var y = cars.sort(); // The sort() method sorts arrays
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
Try it Yourself »
The length property is always one more than the highest array index.
114
www.Sohrabpoor.com
Example
var fruits, text, fLen, i;
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to
fruits
Try it Yourself »
New element can also be added to an array using the length property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to
fruits
Try it Yourself »
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
115
www.Sohrabpoor.com
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to
fruits
Try it Yourself »
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
Try it Yourself »
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard
object.
After that, all array methods and properties will produce incorrect
results.
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
Try it Yourself »
116
www.Sohrabpoor.com
Use [] instead.
These two different statements both create a new empty array named
points:
Try it Yourself »
The new keyword only complicates the code. It can also produce some
unexpected results:
var points = new Array(40, 100); // Creates an array with two elements
(40 and 100)
117
www.Sohrabpoor.com
Try it Yourself »
Try it Yourself »
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
Try it Yourself »
Solution 2:
To solve this problem you can create your own isArray() function:
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
Try it Yourself »
Or more precisely: it returns true if the object prototype contains the word
"Array".
118
www.Sohrabpoor.com
Solution 3:
The instanceof operator returns true if an object is created by a given
constructor:
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result
Banana,Orange,Apple,Mango
Try it Yourself »
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Example
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result
Banana * Orange * Apple * Mango
Try it Yourself »
119
www.Sohrabpoor.com
Popping
The pop() method removes the last element from an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from
fruits
Try it Yourself »
The pop() method returns the value that was "popped out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
Try it Yourself »
Pushing
The push() method adds a new element to an array (at the end):
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
Try it Yourself »
120
www.Sohrabpoor.com
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
Try it Yourself »
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the
last.
The shift() method removes the first array element and "shifts" all other
elements to a lower index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from
fruits
Try it Yourself »
The unshift() method adds a new element to an array (at the beginning),
and "unshifts" older elements:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
Try it Yourself »
The shift() method returns the string that was "shifted out".
Changing Elements
Array elements are accessed using their index number:
Array indexes start with 0. [0] is the first array element, [1] is the second,
[2] is the third ...
121
www.Sohrabpoor.com
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to
"Kiwi"
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
Try it Yourself »
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Try it Yourself »
Using delete may leave undefined holes in the array. Use pop() or shift()
instead.
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
Try it Yourself »
122
www.Sohrabpoor.com
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
Try it Yourself »
The first parameter (0) defines the position where new elements should
be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Joining Arrays
The concat() method creates a new array by concatenating two arrays:
Example
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins)
myGirls and myBoys
Try it Yourself »
123
www.Sohrabpoor.com
Example
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with
arr2 and arr3
document.getElementById("demo").innerHTML = myChildren;
Try it Yourself »
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1
("Orange"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
Try it Yourself »
The slice() method creates a new array. It does not remove any elements
from the source array.
This example slices out a part of an array starting from array element 3
("Apple"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(3);
Try it Yourself »
The method then selects elements from the start argument, and up to (but
not including) the end argument.
124
www.Sohrabpoor.com
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
Try it Yourself »
If the end argument is omitted, like in the first examples, the slice() method
slices out the rest of the array.
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(2);
Try it Yourself »
Because of this, all these examples will produce the same result:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Try it Yourself »
125
www.Sohrabpoor.com
Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.
The reference contains descriptions and examples of all Array properties and
methods.
Sorting an Array
The sort() method sorts an array alphabetically:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
Try it Yourself »
Reversing an Array
The reverse() method reverses the elements in an array.
126
www.Sohrabpoor.com
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
Try it Yourself »
Numeric Sort
By default, the sort() function sorts values as strings.
Because of this, the sort() method will produce incorrect result when sorting
numbers.
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Try it Yourself »
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
Try it Yourself »
127
www.Sohrabpoor.com
When the sort() function compares two values, it sends the values to the
compare function, and sorts the values according to the returned (negative,
zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare
function(40,100).
You can use this code snippet to experiment with numerically and
alphabetically sorting:
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
Try it Yourself »
128
www.Sohrabpoor.com
Try it Yourself »
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
Try it Yourself »
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
Try it Yourself »
Example
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];
129
www.Sohrabpoor.com
Even if objects have properties of different data types, the sort() method can
be used to sort the array.
Example
cars.sort(function(a, b){return a.year - b.year});
Try it Yourself »
Example
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
Try it Yourself »
JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.
Boolean Values
Very often, in programming, you will need a data type that can only have
one of two values, like
YES / NO
ON / OFF
TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the
values true or false.
130
www.Sohrabpoor.com
Example
Boolean(10 > 9) // returns true
Try it Yourself »
Or even easier:
Example
(10 > 9) // also returns true
10 > 9 // also returns true
Try it Yourself »
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
5 < 6
Try it Yourself »
var x = 0;
Boolean(x); // returns false
Try it Yourself »
var x = -0;
Boolean(x); // returns false
Try it Yourself »
var x = "";
Boolean(x); // returns false
Try it Yourself »
132
www.Sohrabpoor.com
var x;
Boolean(x); // returns false
Try it Yourself »
var x = null;
Boolean(x); // returns false
Try it Yourself »
var x = false;
Boolean(x); // returns false
Try it Yourself »
var x = 10 / "H";
Boolean(x); // returns false
Try it Yourself »
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
133
www.Sohrabpoor.com
Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.
x == 5 true Try it »
134
www.Sohrabpoor.com
You will learn more about the use of conditional statements in the next
chapter of this tutorial.
135
www.Sohrabpoor.com
Logical Operators
Logical operators are used to determine the logic between variables or
values.
Given that x = 6 and y = 3, the table below explains the logical operators:
|| or (x == 5 || y == 5) is false Try it »
Syntax
variablename = (condition) ? value1:value2
Example
var voteable = (age < 18) ? "Too young":"Old enough";
Try it Yourself »
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".
136
www.Sohrabpoor.com
When comparing a string with a number, JavaScript will convert the string to
a number when doing the comparison. An empty string converts to 0. A non-
numeric string converts to NaN which is always false.
When comparing two strings, "2" will be greater than "12", because
(alphabetically) 1 is less than 2.
137
www.Sohrabpoor.com
age = Number(age);
if (isNaN(age)) {
voteable = "Error in input";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
Try it Yourself »
The table above use 4 bits unsigned examples. But JavaScript uses 32-bit
signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6:
138
www.Sohrabpoor.com
Example
x = 5 & 1;
The result in x:
Try it Yourself »
Example
x = 5 | 1;
The result in x:
Try it Yourself »
Example
x = 5 >> 1;
The result in x:
Try it Yourself »
Example
x = 5 << 1;
The result in x:
10
Try it Yourself »
Example
x = ~ 5;
The result in x:
-6
Try it Yourself »
139
www.Sohrabpoor.com
Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions.
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.
Syntax
if (condition) {
block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a
JavaScript error.
Example
Make a "Good day" greeting if the hour is less than 18:00:
140
www.Sohrabpoor.com
Good day
Try it Yourself »
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
Good day
Try it Yourself »
141
www.Sohrabpoor.com
Syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2
is true
} else {
block of code to be executed if the condition1 is false and condition2
is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time
is less than 20:00, create a "Good day" greeting, otherwise a "Good
evening":
Good morning
Try it Yourself »
More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife
Foundation (WWF). By using a random number, there is a 50% chance for
each of the links.
142
www.Sohrabpoor.com
Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
143
www.Sohrabpoor.com
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Friday
Try it Yourself »
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
It is not necessary to break the last case in a switch block. The block breaks
(ends) there anyway.
144
www.Sohrabpoor.com
Example
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
Try it Yourself »
Note from the next example, that cases can share the same code block, and
that the default case does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
145
www.Sohrabpoor.com
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
Try it Yourself »
If default is not the last case in the switch block, remember to end it with a
break.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
Try it Yourself »
146
www.Sohrabpoor.com
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been
executed.
Example
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
Try it Yourself »
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
147
www.Sohrabpoor.com
Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (i
= 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
Example
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
Try it Yourself »
And you can omit statement 1 (like when your values are set before the loop
starts):
Example
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Try it Yourself »
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also
optional.
If statement 2 returns true, the loop will start over again, if it returns false,
the loop will end.
If you omit statement 2, you must provide a break inside the loop.
Otherwise the loop will never end. This will crash your browser. Read about
breaks in a later chapter of this tutorial.
148
www.Sohrabpoor.com
Statement 3
Often statement 3 increases the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is
optional.
Statement 3 can also be omitted (like when you increment your values inside
the loop):
Example
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
Try it Yourself »
Example
var person = {fname:"John", lname:"Doe", age:25};
Try it Yourself »
149
www.Sohrabpoor.com
Syntax
while (condition) {
code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again,
as long as a variable (i) is less than 10:
Example
while (i < 10) {
text += "The number is " + i;
i++;
}
Try it Yourself »
If you forget to increase the variable used in the condition, the loop will
never end. This will crash your browser.
150
www.Sohrabpoor.com
Syntax
do {
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Try it Yourself »
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
The loop in this example uses a for loop to collect the car names from the
cars array:
151
www.Sohrabpoor.com
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}
Try it Yourself »
The loop in this example uses a while loop to collect the car names from the
cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}
Try it Yourself »
152
www.Sohrabpoor.com
The break statement breaks the loop and continues executing the code
after the loop (if any):
Example
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
Try it Yourself »
Example
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Try it Yourself »
JavaScript Labels
To label JavaScript statements you precede the statements with a label name
and a colon:
label:
statements
The break and the continue statements are the only JavaScript statements
that can "jump out of" a code block.
Syntax:
153
www.Sohrabpoor.com
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used
to skip one loop iteration.
The break statement, without a label reference, can only be used to jump
out of a loop or a switch.
With a label reference, the break statement can be used to jump out of any
code block:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
break list;
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}
Try it Yourself »
string
number
boolean
154
www.Sohrabpoor.com
object
function
Object
Date
Array
null
undefined
Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
Try it Yourself »
Please observe:
155
www.Sohrabpoor.com
But, the typeof operator always returns a string containing the type of the
operand.
Example
"John".constructor // Returns "function String() {
[native code] }"
(3.14).constructor // Returns "function Number() {
[native code] }"
false.constructor // Returns "function Boolean() {
[native code] }"
[1,2,3,4].constructor // Returns "function Array() {
[native code] }"
{name:'John', age:34}.constructor // Returns" function Object() {
[native code] }"
new Date().constructor // Returns "function Date() {
[native code] }"
function () {}.constructor // Returns "function Function(){
[native code] }"
Try it Yourself »
You can check the constructor property to find out if an object is an Array
(contains the word "Array"):
Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
Try it Yourself »
You can check the constructor property to find out if an object is a Date
(contains the word "Date"):
156
www.Sohrabpoor.com
Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
Try it Yourself »
Example
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression
Try it Yourself »
Example
x.toString()
(123).toString()
(100 + 23).toString()
Try it Yourself »
In the chapter Number Methods, you will find more methods that can be
used to convert numbers to strings:
157
www.Sohrabpoor.com
Method Description
toExponential() Returns a string, with a number rounded and written using exponential
notation.
toFixed() Returns a string, with a number rounded and written with a specified number
of decimals.
Example
Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W.
Europe Daylight Time)"
158
www.Sohrabpoor.com
In the chapter Date Methods, you will find more methods that can be used to
convert dates to strings:
Method Description
159
www.Sohrabpoor.com
In the chapter Number Methods, you will find more methods that can be
used to convert strings to numbers:
Method Description
Example
var y = "5"; // y is a string
var x = + y; // x is a number
Try it Yourself »
If the variable cannot be converted, it will still become a number, but with
the value NaN (Not a number):
Example
var y = "John"; // y is a string
var x = + y; // x is a number (NaN)
Try it Yourself »
160
www.Sohrabpoor.com
Number(false) // returns 0
Number(true) // returns 1
d = new Date();
Number(d) // returns 1404568027739
d = new Date();
d.getTime() // returns 1404568027739
Try it Yourself »
161
www.Sohrabpoor.com
document.getElementById("demo").innerHTML = myVar;
Numbers and booleans are also converted, but this is not very visible:
162
www.Sohrabpoor.com
163
www.Sohrabpoor.com
The search pattern can be used for text search and text replace
operations.
When you search for data in a text, you can use this search pattern to
describe what you are searching for.
164
www.Sohrabpoor.com
Syntax
/pattern/modifiers;
Example
var patt = /w3schools/i;
Example explained:
Try it Yourself »
165
www.Sohrabpoor.com
Example
Use a string to do a search for "W3schools" in a string:
Try it Yourself »
Visit W3Schools!
Try it Yourself »
Try it Yourself »
166
www.Sohrabpoor.com
Modifier Description
g Perform a global match (find all matches rather than stopping after the first
match)
Expression Description
167
www.Sohrabpoor.com
Metacharacter Description
\d Find a digit
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifier Description
168
www.Sohrabpoor.com
Using test()
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
var patt = /e/;
patt.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
Try it Yourself »
You don't have to put the regular expression in a variable first. The two lines
above can be shortened to one:
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
169
www.Sohrabpoor.com
Example 1
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
Try it Yourself »
The try statement lets you test a block of code for errors.
The finally statement lets you execute code, after try and catch,
regardless of the result.
Errors can be coding errors made by the programmer, errors due to wrong
input, and other unforeseeable things.
170
www.Sohrabpoor.com
Example
In this example we have written alert as adddlert to deliberately produce an
error:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
Try it Yourself »
The catch block catches addlert as an error, and executes code to handle
it.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
171
www.Sohrabpoor.com
The technical term for this is: JavaScript will raise (or throw) an
exception.
If you use throw together with try and catch, you can control program flow
and generate custom error messages.
The exception (err) is caught by the catch statement and a custom error
message is displayed:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
172
www.Sohrabpoor.com
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
Try it Yourself »
HTML Validation
The code above is just an example.
Modern browsers will often use a combination of JavaScript and built-in HTML
validation, using predefined validation rules defined in HTML attributes:
You can read more about forms validation in a later chapter of this tutorial.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
173
www.Sohrabpoor.com
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
Try it Yourself »
JavaScript Debugging
It is easy to get lost writing JavaScript code without a debugger.
JavaScript Debugging
It is difficult to write JavaScript code without a debugger.
Your code might contain syntax errors, or logical errors, that are difficult to
diagnose.
Often, when JavaScript code contains errors, nothing will happen. There are
no error messages, and you will get no indications where to search for
errors.
174
www.Sohrabpoor.com
Normally, errors will happen, every time you try to write some new
JavaScript code.
JavaScript Debuggers
Searching for errors in programming code is called code debugging.
Debugging is not easy. But fortunately, all modern browsers have a built-in
debugger.
With a debugger, you can also set breakpoints (places where code execution
can be stopped), and examine variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate
debugging in your browser with the F12 key, and select "Console" in the
debugger menu.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Try it Yourself »
175
www.Sohrabpoor.com
Setting Breakpoints
In the debugger window, you can set breakpoints in the JavaScript code.
At each breakpoint, JavaScript will stop executing, and let you examine
JavaScript values.
After examining values, you can resume the execution of code (typically with
a play button).
With the debugger turned on, this code will stop executing before it executes
the third line.
Example
var x = 15 * 5;
debugger;
document.getElementbyId("demo").innerHTML = x;
Try it Yourself »
176
www.Sohrabpoor.com
Chrome
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Firefox Firebug
Open the browser.
Go to the web page:
http://www.getfirebug.com
Follow the instructions how to:
install Firebug
Internet Explorer
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Opera
Open the browser.
Go to the webpage:
http://dev.opera.com
Follow the instructions how to:
add a Developer Console button to your toolbar.
Safari Firebug
Open the browser.
Go to the webpage:
http://extensions.apple.com
Follow the instructions how to:
install Firebug Lite.
177
www.Sohrabpoor.com
JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top.
Example 1
x = 5; // Assign 5 to x
var x; // Declare x
Try it Yourself »
Example 2
var x; // Declare x
x = 5; // Assign 5 to x
178
www.Sohrabpoor.com
Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y
Try it Yourself »
Example 2
var x = 5; // Initialize x
var y = 7; // Initialize y
Try it Yourself »
This is because only the declaration (var y), not the initialization (=7) is
hoisted to the top.
179
www.Sohrabpoor.com
Example
var x = 5; // Initialize x
var y; // Declare y
y = 7; // Assign 7 to y
Try it Yourself »
To avoid bugs, always declare all variables at the beginning of every scope.
Since this is how JavaScript interprets the code, it is always a good rule.
JavaScript in strict mode does not allow variables to be used if they are not
declared.
Study "use strict" in the next chapter.
180
www.Sohrabpoor.com
The purpose of "use strict" is to indicate that the code should be executed in
"strict mode".
With strict mode, you can not, for example, use undeclared variables.
Declared at the beginning of a script, it has global scope (all code in the
script will execute in strict mode):
Example
"use strict";
x = 3.14; // This will cause an error (x is not defined)
Try it Yourself »
Example
"use strict";
myFunction();
function myFunction() {
y = 3.14; // This will also cause an error (y is not defined)
}
Try it Yourself »
Declared inside a function, it has local scope (only the code inside the
function is in strict mode):
function myFunction() {
"use strict";
y = 3.14; // This will cause an error (y is not defined)
181
www.Sohrabpoor.com
Try it Yourself »
Strict mode changes previously accepted "bad syntax" into real errors.
"use strict";
x = 3.14; // This will cause an error (x is not defined)
182
www.Sohrabpoor.com
Try it Yourself »
"use strict";
x = {p1:10, p2:20}; // This will cause an error (x is not defined)
Try it Yourself »
"use strict";
var x = 3.14;
delete x; // This will cause an error
Try it Yourself »
"use strict";
function x(p1, p2) {};
delete x; // This will cause an error
Try it Yourself »
"use strict";
function x(p1, p1) {}; // This will cause an error
Try it Yourself »
"use strict";
var x = 010; // This will cause an error
Try it Yourself »
"use strict";
var x = \010; // This will cause an error
Try it Yourself »
183
www.Sohrabpoor.com
"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});
Try it Yourself »
"use strict";
var obj = {get x() {return 0} };
Try it Yourself »
"use strict";
delete Object.prototype; // This will cause an error
Try it Yourself »
"use strict";
var eval = 3.14; // This will cause an error
Try it Yourself »
"use strict";
var arguments = 3.14; // This will cause an error
Try it Yourself »
"use strict";
with (Math){x = cos(2)}; // This will cause an error
Try it Yourself »
For security reasons, eval() is not allowed to create variables in the scope
from which it was called:
184
www.Sohrabpoor.com
"use strict";
eval ("var x = 2");
alert (x); // This will cause an error
Try it Yourself »
In function calls like f(), the this value was the global object. In strict mode,
it is now undefined.
Future Proof!
Future reserved keywords are not allowed in strict mode. These are:
implements
interface
let
package
private
protected
public
static
yield
"use strict";
var public = 1500; // This will cause an error
Try it Yourself »
Watch Out!
The "use strict" directive is only recognized at the beginning of a script or a
function.
185
www.Sohrabpoor.com
Variable Names
At W3schools we use camelCase for identifier names (variables and
functions).
At the bottom of this page, you will find a wider discussion about naming
rules.
firstName = "John";
lastName = "Doe";
price = 19.90;
tax = 0.20;
186
www.Sohrabpoor.com
Examples:
var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];
Code Indentation
Always use 4 spaces for indentation of code blocks:
Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Do not use tabs (tabulators) for indentation. Different editors interpret tabs
differently.
Statement Rules
General rules for simple statements:
Examples:
var values = ["Volvo", "Saab", "Fiat"];
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
187
www.Sohrabpoor.com
Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Loops:
for (i = 0; i < 5; i++) {
x += i;
}
Conditionals:
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Object Rules
General rules for object definitions:
Place the opening bracket on the same line as the object name.
Use colon plus one space between each property and its value.
Use quotes around string values, not around numeric values.
Do not add a comma after the last property-value pair.
Place the closing bracket on a new line, without leading spaces.
Always end an object definition with a semicolon.
Example
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
188
www.Sohrabpoor.com
eyeColor: "blue"
};
Short objects can be written compressed, on one line, using spaces only
between properties, like this:
If a JavaScript statement does not fit on one line, the best place to break it,
is after an operator or a comma.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself »
Naming Conventions
Always use the same naming convention for all your code. For example:
189
www.Sohrabpoor.com
Underscores:
PascalCase:
camelCase:
Do not start names with a $ sign. It will put you in conflict with many
JavaScript library names.
<script src="myscript.js"></script>
190
www.Sohrabpoor.com
File Extensions
HTML files should have a .html extension (not .htm).
If you use a mix of upper and lower case, you have to be extremely
consistent.
If you move from a case insensitive, to a case sensitive server, even small
errors can break your web site.
To avoid these problems, always use lower case file names (if possible).
Performance
Coding conventions are not used by computers. Most rules have little impact
on the execution of programs.
191
www.Sohrabpoor.com
Local variables must be declared with the var keyword, otherwise they will
become global variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or
function.
This will:
192
www.Sohrabpoor.com
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
// Use later
for (i = 0; i < 5; i++) {
Initialize Variables
It is a good coding practice to initialize variables when you declare them.
This will:
Initializing variables provides an idea of the intended use (and intended data
type).
193
www.Sohrabpoor.com
Declaring these types as objects, slows down execution speed, and produces
nasty side effects:
Example
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Try it Yourself »
Or even worse:
Example
var x = new String("John");
var y = new String("John");
(x == y) // is false because you cannot compare objects.
Try it Yourself »
Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
194
www.Sohrabpoor.com
Try it Yourself »
JavaScript is loosely typed. A variable can contain different data types, and a
variable can change its data type:
Example
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
Try it Yourself »
Example
var x = 5 + 7; // x.valueOf() is 12, typeof x is a number
var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
var x = "5" + 7; // x.valueOf() is 57, typeof x is a string
var x = 5 - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
var x = "5" - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number
Try it Yourself »
Subtracting a string from a string, does not generate an error but returns
NaN (Not a Number):
Example
"Hello" - "Dolly" // returns NaN
Try it Yourself »
195
www.Sohrabpoor.com
Example
0 == ""; // true
1 == "1"; // true
1 == true; // true
Try it Yourself »
Undefined values can break your code. It is a good habit to assign default
values to arguments.
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
Try it Yourself »
196
www.Sohrabpoor.com
Example
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
}
Try it Yourself »
197
www.Sohrabpoor.com
This if statement returns false (as expected) because x is not equal to 10:
var x = 0;
if (x == 10)
Try it Yourself »
var x = 0;
if (x = 10)
Try it Yourself »
var x = 0;
if (x = 0)
Try it Yourself »
var x = 10;
var y = "10";
if (x == y)
Try it Yourself »
198
www.Sohrabpoor.com
In strict comparison, data type does matter. This if statement returns false:
var x = 10;
var y = "10";
if (x === y)
Try it Yourself »
var x = 10;
switch(x) {
case 10: alert("Hello");
}
Try it Yourself »
var x = 10;
switch(x) {
case "10": alert("Hello");
}
Try it Yourself »
Try it Yourself »
199
www.Sohrabpoor.com
var x = 10;
var y = 5;
var z = x + y; // the result in z is 15
var x = 10;
var y = "5";
var z = x + y; // the result in z is "105"
Try it Yourself »
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point
numbers (Floats).
var x = 0.1;
var y = 0.2;
var z = x + y // the result in z will not be 0.3
Try it Yourself »
Example
var z = (x * 10 + y * 10) / 10; // z will be 0.3
Try it Yourself »
Example 1
var x =
"Hello World!";
Try it Yourself »
200
www.Sohrabpoor.com
Example 2
var x = "Hello
World!";
Try it Yourself »
Example 3
var x = "Hello \
World!";
Try it Yourself »
Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of
the value of x:
if (x == 19);
{
// code block
}
Try it Yourself »
Because of this, these two examples will return the same result:
Example 1
function myFunction(a) {
var power = 10
return a * power
}
Try it Yourself »
201
www.Sohrabpoor.com
Example 2
function myFunction(a) {
var power = 10;
return a * power;
}
Try it Yourself »
JavaScript will also allow you to break a statement into two lines.
Example 3
function myFunction(a) {
var
power = 10;
return a * power;
}
Try it Yourself »
But, what will happen if you break the return statement in two lines like this:
Example 4
function myFunction(a) {
var
power = 10;
return
a * power;
}
Try it Yourself »
Example 5
function myFunction(a) {
var
power = 10;
return;
a * power;
}
Try it Yourself »
202
www.Sohrabpoor.com
Explanation
If a statement is incomplete like:
var
JavaScript will try to complete the statement by reading the next line:
power = 10;
return
return;
JavaScript will close the return statement at the end of the line, because it is
a complete statement.
Arrays with named indexes are called associative arrays (or hashes).
Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
Try it Yourself »
203
www.Sohrabpoor.com
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:
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
Try it Yourself »
Correct:
points = [40, 100, 1, 5, 25, 10];
Correct:
person = {firstName:"John", lastName:"Doe", age:46}
204
www.Sohrabpoor.com
If you want to test if an object exists, this will throw an error if the object is
undefined:
Incorrect:
if (myObj !== null && typeof myObj !== "undefined")
Correct:
if (typeof myObj !== "undefined" && myObj !== null)
Example
for (var i = 0; i < 10; i++) {
// some code
}
return i;
Try it Yourself »
JavaScript Performance
How to speed up your JavaScript code.
205
www.Sohrabpoor.com
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.
Bad Code:
var i;
for (i = 0; i < arr.length; i++) {
Better Code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
The bad code accesses the length property of an array each time the loop is
iterated.
The better code accesses the length property outside the loop, and makes
the loop run faster.
If you expect to access a DOM element several times, access it once, and use
it as a local variable:
Example
var obj;
obj = document.getElementById("demo");
obj.innerHTML = "Hello";
Try it Yourself »
206
www.Sohrabpoor.com
This will always improve page loading, and speed up rendering (page
display), especially on smaller devices.
With this:
While a script is downloading, the browser will not start any other downloads.
In addition all parsing and rendering activity might be blocked.
The HTTP specification defines that browsers should not download more than
two components in parallel.
If possible, you can add your script to the page by code, after the page has
loaded:
207
www.Sohrabpoor.com
Example
<script>
window.onload = downScripts;
function downScripts() {
var element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
}
</script>
JavaScript Standards
ECMAScript 3 (ES3) was released in December 1999.
ECMAScript 6 (ES6) was released in June 2015, and is the latest official
version of JavaScript.
Time passes, and we are now beginning to see complete support for ES5/ES6
in all modern browsers.
208
www.Sohrabpoor.com
209
www.Sohrabpoor.com
210
www.Sohrabpoor.com
In HTML you must (for portability you should) avoid using the name of HTML
and Windows objects and properties:
211
www.Sohrabpoor.com
Examples:
212
www.Sohrabpoor.com
JavaScript JSON
JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.
What is JSON?
JSON stands for JavaScript Object Notation
JSON is lightweight data interchange format
JSON is language independent *
JSON is "self-describing" and easy to understand
* The JSON syntax is derived from JavaScript object notation syntax, but the
JSON format is text only. Code for reading and generating JSON data can be
written in any programming language.
JSON Example
This JSON syntax defines an employees object: an array of 3 employee
records (objects):
JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
213
www.Sohrabpoor.com
Because of this similarity, a JavaScript program can easily convert JSON data
into native JavaScript objects.
"firstName":"John"
JSON Objects
JSON objects are written inside curly braces.
{"firstName":"John", "lastName":"Doe"}
214
www.Sohrabpoor.com
JSON Arrays
JSON arrays are written inside square brackets.
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
Each object is a record of a person (with a first name and a last name).
For simplicity, this can be demonstrated using a string as input (or read more
in our JSON tutorial):
Then, use the JavaScript built-in function JSON.parse() to convert the string
into a JavaScript object:
215
www.Sohrabpoor.com
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
Try it Yourself »
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:
JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
Try it Yourself »
216
www.Sohrabpoor.com
Submit
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
<input id="numb">
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
</body>
</html>
If a form field (fname) is empty, the required attribute prevents this form
from being submitted:
217
www.Sohrabpoor.com
Try it Yourself »
// Action:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>
Data Validation
Data validation is the process of ensuring that computer input is clean,
correct, and useful.
Server side validation is performed by a web server, after input has been
sent to the server.
218
www.Sohrabpoor.com
219
www.Sohrabpoor.com
220
www.Sohrabpoor.com
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML =
inpObj.validationMessage;
}
}
</script>
Try it Yourself »
221
www.Sohrabpoor.com
Validity Properties
The validity property of an input element contains a number of properties
related to the validity of data:
Property Description
patternMismatch Set to true, if an element's value does not match its pattern
attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
222
www.Sohrabpoor.com
Examples
If the number in an input field is greater than 100 (the input's max
attribute), display a message:
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeOverflow) {
txt = "Value too large";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
Try it Yourself »
If the number in an input field is less than 100 (the input's min attribute),
display a message:
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeUnderflow) {
txt = "Value too small";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
Try it Yourself »
223
www.Sohrabpoor.com
JavaScript Objects
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand
JavaScript.
Primitive values are: strings ("John Doe"), numbers (3.14), true, false, null,
and undefined.
Example
var person = "John Doe";
Try it Yourself »
Objects are variables too. But objects can contain many values.
The values are written as name : value pairs (name and value separated by
a colon).
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Try it Yourself »
224
www.Sohrabpoor.com
Object Properties
The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
225
www.Sohrabpoor.com
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
JavaScript objects are containers for named values, called properties and
methods.
226
www.Sohrabpoor.com
Using an object literal, you both define and create an object in one
statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces
{}.
The following example creates a new JavaScript object with four properties:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Try it Yourself »
Spaces and line breaks are not important. An object definition can span
multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Try it Yourself »
Example
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Try it Yourself »
227
www.Sohrabpoor.com
The two examples above do exactly the same. There is no need to use new
Object().
For simplicity, readability and execution speed, use the first one (the object
literal method).
Sometimes we like to have an "object type" that can be used to create many
objects of one type.
Example
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
Try it yourself »
Once you have an object constructor, you can create new objects of the
same type:
228
www.Sohrabpoor.com
The value of this, when used in a function, is the object that "owns" the
function.
The this keyword in an object constructor does not have a value. It is only a
substitute for the new object.
The value of this will become the new object when the constructor is used to
create an object.
Note that this is not a variable. It is a keyword. You cannot change the value
of this.
Example
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object
Try it Yourself »
The Math() object is not in the list. Math is a global object. The new keyword
cannot be used on Math.
229
www.Sohrabpoor.com
And there is no reason to use new Array(). Use array literals instead: []
And there is no reason to use new RegExp(). Use pattern literals instead: /()/
And there is no reason to use new Object(). Use object literals instead: {}
Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/ // new regexp object
var x7 = function(){}; // new function object
Try it Yourself »
The object x is not a copy of person. It is person. Both x and person is the
same object.
Any changes to x will also change person, because x and person are the
same object.
230
www.Sohrabpoor.com
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
var x = person;
x.age = 10; // This will change both x.age and person.age
Try it Yourself »
JavaScript Properties
Properties are the values associated with a JavaScript object.
Properties can usually be changed, added, and deleted, but some are read
only.
objectName.property // person.age
or
objectName["property"] // person["age"]
or
231
www.Sohrabpoor.com
Example 1
person.firstname + " is " + person.age + " years old.";
Try it Yourself »
Example 2
person["firstname"] + " is " + person["age"] + " years old.";
Try it Yourself »
Syntax
for (variable in object) {
code to be executed
}
The block of code inside of the for...in loop will be executed once for each
property.
Example
var person = {fname:"John", lname:"Doe", age:25};
for (x in person) {
txt += person[x];
}
Try it Yourself »
Assume that the person object already exists - you can then give it new
properties:
232
www.Sohrabpoor.com
Example
person.nationality = "English";
Try it Yourself »
You cannot use reserved words for property (or method) names. JavaScript
naming rules apply.
Deleting Properties
The delete keyword deletes a property from an object:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];
Try it Yourself »
The delete keyword deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.
Property Attributes
All properties have a name. In addition they also have a value.
These attributes define how the property can be accessed (is it readable?, is
it writable?)
233
www.Sohrabpoor.com
In JavaScript, all attributes can be read, but only the value attribute can be
changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property
attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a
prototype property, it will affect all objects inherited from the prototype.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
234
www.Sohrabpoor.com
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a
property.
The fullName property will execute (as a function) when it is invoked with ().
Example
name = person.fullName();
Try it Yourself »
If you access the fullName property, without (), it will return the function definition:
Example
name = person.fullName;
Try it Yourself »
HELLO WORLD!
235
www.Sohrabpoor.com
Example
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}
The changeName() function assigns the value of name to the person's lastName property.
JavaScript knows which person you are talking about by "substituting" this with myMother.
All JavaScript objects inherit their properties and methods from their
prototype.
JavaScript Prototypes
All JavaScript objects inherit the properties and methods from their
prototype.
Objects created using an object literal, or with new Object(), inherit from a
prototype called Object.prototype.
236
www.Sohrabpoor.com
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the
Object.prototype.
Creating a Prototype
The standard way to create an object prototype is to use an object
constructor function:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
With a constructor function, you can use the new keyword to create new
objects from the same prototype:
Example
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
Try it Yourself »
Sometimes you want to add new properties (or methods) to all existing
objects of a given type.
237
www.Sohrabpoor.com
Example
myFather.nationality = "English";
Try it Yourself »
The property will be added to myFather. Not to myMother. Not to any other
person objects.
Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};
Try it Yourself »
Example
Person.nationality = "English";
Try it Yourself »
238
www.Sohrabpoor.com
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English"
}
Try it Yourself »
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}
Try it Yourself »
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
Try it Yourself »
239
www.Sohrabpoor.com
The JavaScript prototype property also allows you to add new methods to an
existing prototype:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Try it Yourself »
Only modify your own prototypes. Never modify the prototypes of standard
JavaScript objects.
Function Declarations
Earlier in this tutorial, you learned that functions are declared with the
following syntax:
function functionName(parameters) {
code to be executed
}
Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are invoked (called upon).
240
www.Sohrabpoor.com
Example
function myFunction(a, b) {
return a * b;
}
Try it Yourself »
Function Expressions
A JavaScript function can also be defined using an expression.
Example
var x = function (a, b) {return a * b};
Try it Yourself »
After a function expression has been stored in a variable, the variable can be
used as a function:
Example
var x = function (a, b) {return a * b};
var z = x(4, 3);
Try it Yourself »
Functions stored in variables do not need function names. They are always
invoked (called) using the variable name.
241
www.Sohrabpoor.com
Example
var myFunction = new Function("a", "b", "return a * b");
Try it Yourself »
You actually don't have to use the function constructor. The example above
is the same as writing:
Example
var myFunction = function (a, b) {return a * b};
Try it Yourself »
Most of the time, you can avoid using the new keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about "hoisting".
Because of this, JavaScript functions can be called before they are declared:
myFunction(5);
function myFunction(y) {
return y * y;
}
242
www.Sohrabpoor.com
Self-Invoking Functions
Function expressions can be made "self-invoking".
Example
(function () {
var x = "Hello!!"; // I will invoke myself
})();
Try it Yourself »
Example
function myFunction(a, b) {
return a * b;
}
Try it Yourself »
243
www.Sohrabpoor.com
Example
function myFunction(a, b) {
return a * b;
}
var x = myFunction(4, 3) * 2;
Try it Yourself »
Example
function myFunction(a, b) {
return arguments.length;
}
Try it Yourself »
Example
function myFunction(a, b) {
return a * b;
}
Try it Yourself »
244
www.Sohrabpoor.com
Function arguments are the real values passed to (and received by) the
function.
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
Parameter Defaults
If a function is called with missing arguments (less than declared), the
missing values are set to: undefined
245
www.Sohrabpoor.com
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
Try it Yourself »
The argument object contains an array of the arguments used when the
function was called (invoked).
This way you can simply use a function to find (for instance) the highest
value in a list of numbers:
Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Try it Yourself »
246
www.Sohrabpoor.com
Example
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
Try it Yourself »
JavaScript arguments are passed by value: The function only gets to know
the values, not the argument's locations.
Because of this, objects will behave like they are passed by reference:
247
www.Sohrabpoor.com
The value of this, when used in a function, is the object that "owns" the
function.
Note that this is not a variable. It is a keyword. You cannot change the value
of this.
Some people use the term "call a function" instead of "invoke a function".
248
www.Sohrabpoor.com
Try it Yourself »
The function above does not belong to any object. But in JavaScript there is
always a default global object.
In HTML the default global object is the HTML page itself, so the function
above "belongs" to the HTML page.
In a browser the page object is the browser window. The function above
automatically becomes a window function.
Example
function myFunction(a, b) {
return a * b;
}
window.myFunction(10, 2); // window.myFunction(10, 2) will also return
20
Try it Yourself »
This is a common way to invoke a JavaScript function, but not a very good
practice.
Global variables, methods, or functions can easily create name conflicts and
bugs in the global object.
249
www.Sohrabpoor.com
Example
function myFunction() {
return this;
}
myFunction(); // Will return the window object
Try it Yourself »
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"
Try it Yourself »
The thing called this, is the object that "owns" the JavaScript code. In this
case the value of this is myObject.
Test it! Change the fullName method to return the value of this:
250
www.Sohrabpoor.com
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
myObject.fullName(); // Will return [object Object] (the owner
object)
Try it Yourself »
It looks like you create a new function, but since JavaScript functions are
objects you actually create a new object:
Example
// This is a function constructor:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
Try it Yourself »
A constructor invocation creates a new object. The new object inherits the
properties and methods from its constructor.
251
www.Sohrabpoor.com
Example
function myFunction(a, b) {
return a * b;
}
myObject = myFunction.call(myObject, 10, 2); // Will return 20
Try it Yourself »
Example
function myFunction(a, b) {
return a * b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray); // Will also return 20
Try it Yourself »
Both methods take an owner object as the first argument. The only
difference is that call() takes the function arguments separately, and apply()
takes the function arguments in an array.
In JavaScript strict mode, the first argument becomes the value of this in
the invoked function, even if the argument is not an object.
With call() or apply() you can set the value of this, and invoke a function as
a new method of an existing object.
252
www.Sohrabpoor.com
JavaScript Closures
JavaScript variables can belong to the local or global scope.
Global Variables
A function can access all variables defined inside the function, like this:
Example
function myFunction() {
var a = 4;
return a * a;
}
Try it Yourself »
But a function can also access variables defined outside the function, like
this:
Example
var a = 4;
function myFunction() {
return a * a;
}
Try it Yourself »
Global variables can be used (and changed) by all scripts in the page (and in
the window).
A local variable can only be used inside the function where it is defined. It is
hidden from other functions and other scripting code.
253
www.Sohrabpoor.com
Global and local variables with the same name are different variables.
Modifying one, does not modify the other.
Variables created without the keyword var, are always global, even if they
are created inside a function.
Variable Lifetime
Global variables live as long as your application (your window / your web
page) lives.
Local variables have short lives. They are created when the function is
invoked, and deleted when the function is finished.
A Counter Dilemma
Suppose you want to use a variable for counting something, and you want
this counter to be available to all functions.
You could use a global variable, and a function to increase the counter:
Example
var counter = 0;
function add() {
counter += 1;
}
add();
add();
add();
Try it Yourself »
The problem is, that any script on the page can change the counter, without
calling add().
254
www.Sohrabpoor.com
If I declare the counter inside the function, nobody will be able to change it
without calling add():
Example
function add() {
var counter = 0;
counter += 1;
}
add();
add();
add();
Try it Yourself »
It did not work! Every time I call the add() function, the counter is set to 1.
In fact, in JavaScript, all functions have access to the scope "above" them.
Example
function add() {
var counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}
Try it Yourself »
255
www.Sohrabpoor.com
We need a closure.
JavaScript Closures
Remember self-invoking functions? What does this function do?
Example
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
Try it Yourself »
Example Explained
The variable add is assigned the return value of a self-invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and
returns a function expression.
This way add becomes a function. The "wonderful" part is that it can access
the counter in the parent scope.
The counter is protected by the scope of the anonymous function, and can
only be changed using the add function.
A closure is a function having access to the parent scope, even after the
parent function has closed.
256
www.Sohrabpoor.com
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
257
www.Sohrabpoor.com
In other words: The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
258
www.Sohrabpoor.com
HTML DOM properties are values (of HTML Elements) that you can set or
change.
A property is a value that you can get or set (like changing the content of
an HTML element).
Example
The following example changes the content (the innerHTML) of the <p>
element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
Try it Yourself »
259
www.Sohrabpoor.com
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
If you want to access any element in an HTML page, you always start with
accessing the document object.
Below are some examples of how you can use the document object to access
and manipulate HTML.
260
www.Sohrabpoor.com
261
www.Sohrabpoor.com
262
www.Sohrabpoor.com
Later, in HTML DOM Level 3, more objects, collections, and properties were
added.
263
www.Sohrabpoor.com
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
264
www.Sohrabpoor.com
To do so, you have to find the elements first. There are a couple of ways to
do this:
Example
var myElement = document.getElementById("intro");
Try it Yourself »
265
www.Sohrabpoor.com
If the element is found, the method will return the element as an object (in
myElement).
Example
var x = document.getElementsByTagName("p");
Try it Yourself »
This example finds the element with id="main", and then finds all <p>
elements inside "main":
Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
Try it Yourself »
Example
var x = document.getElementsByClassName("intro");
Try it Yourself »
Finding elements by class name does not work in Internet Explorer 8 and
earlier versions.
266
www.Sohrabpoor.com
Example
var x = document.querySelectorAll("p.intro");
Try it Yourself »
Example
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
Try it Yourself »
The following HTML objects (and object collections) are also accessible:
document.anchors
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
267
www.Sohrabpoor.com
document.links
document.scripts
document.title
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Try it Yourself »
268
www.Sohrabpoor.com
Example
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Try it Yourself »
Example
<!DOCTYPE html>
<html>
<body>
<script>
var element = document.getElementById("header");
element.innerHTML = "New Header";
</script>
</body>
</html>
Try it Yourself »
269
www.Sohrabpoor.com
Example explained:
document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Try it Yourself »
Example explained:
270
www.Sohrabpoor.com
document.getElementById(id).style.property=new style
Example
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Try it Yourself »
Using Events
The HTML DOM allows you to execute code when an event occurs.
An element is clicked on
The page has loaded
Input fields are changed
271
www.Sohrabpoor.com
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the
user clicks a button:
Example
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Try it Yourself »
More Examples
Visibility How to make an element invisible. Do you want to show the
element or not?
272
www.Sohrabpoor.com
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
Example
<div id ="container">
<div id ="animate">My animation will go here</div>
</div>
273
www.Sohrabpoor.com
Example
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
Try it Yourself »
Animation Code
JavaScript animations are done by programming gradual changes in an
element's style.
The changes are called by a timer. When the timer interval is small, the
animation looks continuous.
Example
var id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
274
www.Sohrabpoor.com
Try it Yourself »
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks
on an HTML element.
onclick=JavaScript
275
www.Sohrabpoor.com
In this example, the content of the <h1> element is changed when a user
clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
Try it Yourself »
Example
Assign an onclick event to a button element:
Try it Yourself »
276
www.Sohrabpoor.com
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
Try it Yourself »
The onload event can be used to check the visitor's browser type and
browser version, and load the proper version of the web page based on the
information.
The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">
Try it Yourself »
277
www.Sohrabpoor.com
Example
<input type="text" id="fname" onchange="upperCase()">
Try it Yourself »
Mouse Over Me
Try it Yourself »
Click Me
Try it Yourself »
278
www.Sohrabpoor.com
More Examples
onmousedown and onmouseup
Change an image when a user holds down the mouse button.
onload
Display an alert box when the page has finished loading.
onfocus
Change the background-color of an input field when it gets focus.
Mouse Events
Change the color of an element when the cursor moves over it.
document.getElementById("myBtn").addEventListener("click", displayDate);
Try it Yourself »
You can add many event handlers of the same type to one element, i.e two
"click" events.
279
www.Sohrabpoor.com
You can add event listeners to any DOM object not only HTML elements. i.e
the window object.
Syntax
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
Note that you don't use the "on" prefix for the event; use "click" instead of
"onclick".
Try it Yourself »
280
www.Sohrabpoor.com
Example
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
Try it Yourself »
Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Try it Yourself »
Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Try it Yourself »
281
www.Sohrabpoor.com
Example
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Try it Yourself »
Passing Parameters
When passing parameter values, use an "anonymous function" that calls the
specified function with the parameters:
Example
element.addEventListener("click", function(){ myFunction(p1, p2); });
Try it Yourself »
In bubbling the inner most element's event is handled first and then the
outer: the <p> element's click event is handled first, then the <div>
element's click event.
In capturing the outer most element's event is handled first and then the
inner: the <div> element's click event will be handled first, then the <p>
element's click event.
With the addEventListener() method you can specify the propagation type by
using the "useCapture" parameter:
The default value is false, which will use the bubbling propagation, when the
value is set to true, the event uses the capturing propagation.
Example
document.getElementById("myP").addEventListener("click",
myFunction, true);
document.getElementById("myDiv").addEventListener("click",
myFunction, true);
Try it Yourself »
Example
element.removeEventListener("mousemove", myFunction);
Try it Yourself »
Browser Support
The numbers in the table specifies the first browser version that fully
supports these methods.
Method
283
www.Sohrabpoor.com
element.attachEvent(event, function);
element.detachEvent(event, function);
Example
Cross-browser solution:
var x = document.getElementById("myBtn");
if (x.addEventListener) { // For all major browsers,
except IE 8 and earlier
x.addEventListener("click", myFunction);
} else if (x.attachEvent) { // For IE 8 and earlier
versions
x.attachEvent("onclick", myFunction);
}
Try it Yourself »
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document
is a node:
284
www.Sohrabpoor.com
With the HTML DOM, all nodes in the node tree can be accessed by
JavaScript.
New nodes can be created, and all nodes can be modified or deleted.
Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
In a node tree, the top node is called the root (or root node)
Every node has exactly one parent, except the root (which has no
parent)
A node can have a number of children
Siblings (brothers or sisters) are nodes with the same parent
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
285
www.Sohrabpoor.com
and:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
286
www.Sohrabpoor.com
Warning !
A common error in DOM processing is to expect an element node to contain
text.
The following example collects the node value of an <h1> element and
copies it into a <p> element:
Example
<html>
<body>
<p id="demo">Hello!</p>
<script>
var myText = document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
Try it Yourself »
287
www.Sohrabpoor.com
Example
<html>
<body>
<script>
myText = document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
Try it Yourself »
Example
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
Try it Yourself »
288
www.Sohrabpoor.com
Example
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates
the <b>document.documentElement</b> property.</p>
</div>
<script>
alert(document.documentElement.innerHTML);
</script>
</body>
</html>
Try it Yourself »
nodeName is read-only
nodeName of an element node is the same as the tag name
nodeName of an attribute node is the attribute name
nodeName of a text node is always #text
nodeName of the document node is always #document
289
www.Sohrabpoor.com
Element 1
Attribute 2
Text 3
Comment 8
Document 9
290
www.Sohrabpoor.com
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
Try it Yourself »
Example Explained
This code creates a new <p> element:
To add text to the <p> element, you must create a text node first. This code
creates a text node:
Then you must append the text node to the <p> element:
para.appendChild(node);
element.appendChild(para);
291
www.Sohrabpoor.com
If you don't want that you can use the insertBefore() method:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
Try it Yourself »
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
Try it Yourself »
292
www.Sohrabpoor.com
Example Explained
This HTML document contains a <div> element with two child nodes (two
<p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
parent.removeChild(child);
Here is a common workaround: Find the child you want to remove, and use
its parentNode property to find the parent:
293
www.Sohrabpoor.com
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
Try it Yourself »
Example
var x = document.getElementsByTagName("p");
The nodes can be accessed by an index number. To access the second <p>
node you can write:
y = x[1];
Try it Yourself »
294
www.Sohrabpoor.com
Example
var myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;
Try it Yourself »
Example explained:
The length property is useful when you want to loop through the nodes in a
node list:
Example
Change the background color of all <p> elements in a node list:
Try it Yourself »
295
www.Sohrabpoor.com
Since modern browsers have implemented (almost) the same methods and
properties for JavaScript interactivity, it is often referred to, as methods and
properties of the BOM.
Even the document object (of the HTML DOM) is a property of the window
object:
window.document.getElementById("header");
document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window.
The browser window (the browser viewport) is NOT including toolbars and
scrollbars.
296
www.Sohrabpoor.com
document.documentElement.clientHeight
document.documentElement.clientWidth
or
document.body.clientHeight
document.body.clientWidth
Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
Try it Yourself »
The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)
Window Screen
The window.screen object can be written without the window prefix.
297
www.Sohrabpoor.com
Properties:
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
Example
Display the width of the screen in pixels:
document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;
Try it Yourself »
Example
Display the height of the screen in pixels:
document.getElementById("demo").innerHTML =
"Screen Height: " + screen.height;
Try it Yourself »
298
www.Sohrabpoor.com
Example
Display the available width of the screen in pixels:
document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;
Try it Yourself »
Example
Display the available height of the screen in pixels:
document.getElementById("demo").innerHTML =
"Available Screen Height: " + screen.availHeight;
Try it Yourself »
299
www.Sohrabpoor.com
All modern computers use 24 bit or 32 bit hardware for color resolution:
Very old computers, and old cell phones used 8 bits: 256 different "VGA
colors".
Example
Display the color depth of the screen in bits:
document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;
Try it Yourself »
Example
Display the pixel depth of the screen in bits:
document.getElementById("demo").innerHTML =
"Screen Pixel Depth: " + screen.pixelDepth;
300
www.Sohrabpoor.com
Try it Yourself »
For modern computers, Color Depth and Pixel Depth are equal.
Window Location
The window.location object can be written without the window prefix.
Some examples:
Example
Display the href (URL) of the current page:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
301
www.Sohrabpoor.com
Result is:
Try it Yourself »
Example
Display the name of the host:
document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;
Result is:
Try it Yourself »
Example
Display the path name of the current URL:
document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;
Result is:
/js/js_window_location.asp
Try it Yourself »
302
www.Sohrabpoor.com
Example
Display the web protocol:
document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;
Result is:
Try it Yourself »
Example
Load a new document:
<html>
<head>
<script>
function newDoc() {
window.location.assign("http://www.w3schools.com")
}
</script>
</head>
<body>
</body>
</html>
Try it Yourself »
303
www.Sohrabpoor.com
Window History
The window.history object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript
can access this object.
Some methods:
Example
Create a back button on a page:
<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>
304
www.Sohrabpoor.com
Example
Create a forward button on a page:
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
</body>
</html>
Window Navigator
The window.navigator object can be written without the window prefix.
Some examples:
navigator.appName
navigator.appCodeName
navigator.platform
305
www.Sohrabpoor.com
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Cookies Enabled is " + navigator.cookieEnabled;
</script>
Try it Yourself »
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " +
navigator.appCodeName;
</script>
Try it Yourself »
Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".
306
www.Sohrabpoor.com
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.product;
</script>
Try it Yourself »
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.appVersion;
</script>
Try it Yourself »
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.userAgent;
</script>
Try it Yourself »
307
www.Sohrabpoor.com
Warning !!!
The information from the navigator object can often be misleading, and
should not be used to detect browser versions because:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.platform;
</script>
Try it Yourself »
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.language;
</script>
Try it Yourself »
308
www.Sohrabpoor.com
Is Java Enabled?
The method javaEnabled() returns true if Java is enabled:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.javaEnabled();
</script>
Try it Yourself »
Alert Box
An alert box is often used if you want to make sure information comes
through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
Example
alert("I am an alert box!");
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
Try it Yourself »
309
www.Sohrabpoor.com
Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
Syntax
window.confirm("sometext");
Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
Try it Yourself »
Prompt Box
A prompt box is often used if you want the user to input a value before
entering a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
Syntax
window.prompt("sometext","defaultText");
310
www.Sohrabpoor.com
Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
Try it Yourself »
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.
Example
alert("Hello\nHow are you?");
Try it Yourself »
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.
The setTimeout() and setInterval() are both methods of the HTML DOM
Window object.
311
www.Sohrabpoor.com
Example
Click a button. Wait 3 seconds, and the page will alert "Hello":
<script>
function myFunction() {
alert('Hello');
}
</script>
Try it Yourself »
window.clearTimeout(timeoutVariable)
If the function has not already been executed, you can stop the execution by
calling the clearTimeout() method:
312
www.Sohrabpoor.com
Example
Same example as above, but with an added "Stop" button:
Try it Yourself »
window.setInterval(function, milliseconds);
The second parameter indicates the length of the time-interval between each
execution.
This example executes a function called "myTimer" once every second (like a
digital watch).
Example
Display the current time:
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
Try it Yourself »
313
www.Sohrabpoor.com
window.clearInterval(timerVariable)
Example
Same example as above, but we have added a "Stop time" button:
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
Try it Yourself »
More Examples
Another simple timing
314
www.Sohrabpoor.com
JavaScript Cookies
Cookies let you store user information in web pages.
When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user.
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
When a browser requests a web page from a server, cookies belonging to the
page is added to the request. This way the server gets the necessary data to
"remember" information about users.
You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:
With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
315
www.Sohrabpoor.com
var x = document.cookie;
Note that you don't have to specify a cookie value when you delete a cookie.
Even if you write a whole cookie string to document.cookie, when you read it
out again, you can only see the name-value pair of it.
316
www.Sohrabpoor.com
If you set a new cookie, older cookies are not overwritten. The new cookie is
added to document.cookie, so if you read document.cookie again you will get
something like:
Display All Cookies Create Cookie 1 Create Cookie 2 Delete Cookie 1 Delete
Cookie 2
If you want to find the value of one specified cookie, you must write a
JavaScript function that searches for the cookie value in the cookie string.
The first time a visitor arrives to the web page, he will be asked to fill in his
name. The name is then stored in a cookie.
The next time the visitor arrives at the same page, he will get a welcome
message.
Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
317
www.Sohrabpoor.com
Example explained:
The parameters of the function above are the name of the cookie (cname),
the value of the cookie (cvalue), and the number of days until the cookie
should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie
value, and the expires string.
Example
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
Function explained:
Create a variable (name) with the text to search for (cname + "=").
Loop through the ca array (i=0;i<ca.length;i++), and read out each value
c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length).
318
www.Sohrabpoor.com
If the cookie is not set, it will display a prompt box, asking for the name of
the user, and stores the username cookie for 365 days, by calling the
setCookie function:
Example
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
319
www.Sohrabpoor.com
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Try it Yourself »
The example above runs the checkCookie() function when the page loads.
JavaScript Examples
What can JavaScript do?
JavaScript can change HTML content
JavaScript can change HTML attributes
JavaScript can change CSS style
JavaScript can hide HTML elements
JavaScript can show hidden HTML elements
Examples explained
JavaScript Output
Writing into an window alert box
Writing into the HTML output
Writing into an HTML element
Writing into the browser console
Output explained
320
www.Sohrabpoor.com
Placement explained
JavaScript Syntax
JavaScript statements
JavaScript numbers
JavaScript strings
JavaScript expressions
JavaScript keywords
JavaScript variables
JavaScript assignment
JavaScript operators
JavaScript comments
JavaScript is case sensitive
Syntax explained
JavaScript Statements
JavaScript statements are commands to the browser
JavaScript code is a sequence of statements
JavaScript statements are separated with semicolon
Multiple statement on one line is allowed
JavaScript statements can be grouped together in code blocks
You can break a code line after an operator or a comma.
Statements explained
321
www.Sohrabpoor.com
JavaScript Comments
Single line comments
Single line comments at the end of a line
Multiple lines comments
Single line comment to prevent execution
Multiple lines comment to prevent execution
Comments explained
JavaScript Variables
JavaScript variables
JavaScript variables as algebra
JavaScript numbers and strings
JavaScript var keyword.
Declaring many variables in one statement
Declaring many variables multiline
A variable without a value returns the value undefined
Re-declaring a variable will not destroy the value
Adding JavaScript numbers
Adding JavaScript strings
Adding strings and numbers
Variables explained
JavaScript Arithmetic
The addition (+) operator
The subtraction (-) operator
The multiplication (*) operator
The division (/) operator
The modulus (%) operator
The increment (++) operator
The decrement (--) operator
Arithmetic explained
322
www.Sohrabpoor.com
JavaScript Assignment
The = assignment operator
The += assignment operator
The -= assignment operator
The *= assignment operator
The /= assignment operator
The %= assignment operator
Assignment explained
Concatenation explained
323
www.Sohrabpoor.com
JavaScript Objects
Create a JavaScript variable
Create a JavaScript object
Create a person object (single line)
Create a person object (multiple lines)
Access object properties using .property
Access object properties using [property]
Access a function property as a method
Access a function property as a property
Objects explained
JavaScript Functions
A simple function
A function with an argument
A function with an argument 2
A function that returns a value
A function that converts Fahrenheit to Celsius
A function call without ()
Functions explained
JavaScript Events
An onclick event changes an HTML element
An onclick event changes its own element
An onclick event calls a function
Events explained
JavaScript Strings
Strings can be written with single or double quotes.
Show some string examples
Backslash before quotes accepts quotes as quotes.
Find the length of a string
324
www.Sohrabpoor.com
Strings explained
JavaScript Numbers
Number are considered accurate only up to 15 digits
Floating point arithmetic is not always 100% accurate
But it helps to multiply and divide by 10
Constants, preceded by 0x, are interpreted as hexadecimal
The toString() method can output numbers as hex, octal, and binary
JavaScript will generate Infinity if you calculate a too large number
Division by zero generates Infinity
A number divided by a string is not a number
Numbers explained
JavaScript Maths
Use Math.random() to return a random number between 0 and 1
Use Math.round() to round a number
Use Math.ceil() to round a number (up)
Use Math.floor() to round a number (down)
Use Math.floor() and random() to return a random integer
Use Math.max() to return the number with the highest value
Use Math.min() to return the number with the lowest value
Convert Celsius to Fahrenheit
Maths explained
325
www.Sohrabpoor.com
JavaScript Dates
Use Date() to display today's date and time
Use getFullYear() display the year
Use getTime() to calculate the number of milliseconds since 1970
Use setFullYear() to set a specific date
Use toUTCString() to convert today's date (according to UTC) to a string
Use getDay() to display the weekday as a number
Use getDay() and an array to display the weekday as a name
Display a clock
Dates explained
JavaScript Arrays
Create an array
Join two arrays - concat()
Join three arrays - concat()
Join all elements of an array into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of the elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetically and ascending) - sort()
Sort numbers (numerically and ascending) - sort()
Sort numbers (numerically and descending) - sort()
Sort numbers (alphabetically and numerically) - sort()
Sort numbers in random order - sort()
Sort objects by numeric properties - sort()
Sort objects by string properties - sort()
Add an element to position 2 in an array - splice()
Convert an array to a string - toString()
Add new elements to the beginning of an array - unshift()
Arrays explained
326
www.Sohrabpoor.com
JavaScript Booleans
Display the value of Boolean(10 > 9)
Display the value of 10 > 9
Everything with a real value is true
The Boolean value of zero is false
The Boolean value of minus zero is false
The Boolean value of an empty string is false
The Boolean value of undefined is false
The Boolean value of null is false
The Boolean value of false is false
The Boolean value of NaN is false
Booleans explained
JavaScript Comparisons
Assign 5 to x, and display the value of (x == 8)
Assign 5 to x, and display the value of (x == 5)
Assign 5 to x, and display the value of (x === 5)
Assign 5 to x, and display the value of (x === "5")
Assign 5 to x, and display the value of (x != 8)
Assign 5 to x, and display the value of (x !== 5)
Assign 5 to x, and display the value of (x !== "5")
Assign 5 to x, and display the value of (x > 8)
Assign 5 to x, and display the value of (x < 8)
Assign 5 to x, and display the value of (x >= 8)
Assign 5 to x, and display the value of (x <= 8)
Comparisons explained
327
www.Sohrabpoor.com
JavaScript Conditionals
The if statement
The else statement
The else if statement
Random link
Switch statement
Conditionals explained
JavaScript Loops
For loop
Looping through HTML headers
While loop
Do While loop
Break a loop
Break and continue a loop
Use a for...in statement to loop through the elements of an object
Loops explained
Errors explained
328
www.Sohrabpoor.com
JavaScript Objects
Creating a JavaScript variable
Creating a JavaScript object
Creating a JavaScript object (single line)
Creating a JavaScript object (multiple lines)
Creating a JavaScript object using new
Creating JavaScript objects using a constructor
Creating built-in JavaScript objects
The best way to create JavaScript variables
JavaScript objects are mutable
Objects explained
329
www.Sohrabpoor.com
CSS Manipulation
Change the visibility of an HTML element
Change the background color of an HTML element
330
www.Sohrabpoor.com
Button Object
Disable a button
Find the name of a button
Find the type of a button
Find the value of a button
Find the text displayed on a button
Find the id of the form a button belongs to
Form Object
Submit a form
Reset a form
331
www.Sohrabpoor.com
Anchor Object
Find the value of the href attribute of a link
Find the value of the hreflang attribute of a link
Find the value of the id attribute a link
Find the value of the rel attribute of a link
Find the value of the target attribute of a link
Find the value of the type attribute of a link
Area Object
Find the alternate text of an image-map area
Find the coordinates of an area
Find the shape of an area
Find the href of an area
Find the protocol part of the href attribute of an area
Find the hostname part of the href attribute of an area
Find the port number part of the href attribute of an area
Find the pathname part of the href attribute of an area
Find the querystring part of the href attribute of an area
Find the hash part of the href attribute of an area
Find the value of the target attribute of an area
332
www.Sohrabpoor.com
Base Object
Find the base URL for all relative URLs on a page
Find the base target for all links on a page
IFrame Object
Change the background color of an iframe
Find the height of an iframe
Find the value of the name attribute of an iframe
Find the source (src) attribute of an iframe
Change the source (src) attribute of an iframe
Image Object
Find the alternate text of an image
Find the height of an image
Click to display a high-resolution version of an image
Find the source (src) of an image
Change the source of an image
Change the source of the lightbulb
Find the value of the usemap attribute of an image
Table Objects
Change the width of a table border
Change the padding of a table
Find the innerHTML of a cell
Create a caption for a table
Delete rows in a table
Add rows to a table
Change the content of a table cell
333
www.Sohrabpoor.com
Input Events
onblur - When a user leaves an input field
onchange - When a user changes the content of an input field
onchange - When a user selects a dropdown value
onfocus - When an input field gets focus
onselect - When input text is selected
onsubmit - When a user clicks the submit button
onreset - When a user clicks the reset button
onkeydown - When a user is pressing/holding down a key
onkeypress - When a user is pressing/holding down a key
onkeyup - When the user releases a key
onkeyup - When the user releases a key
onkeydown vs onkeyup - Both
Mouse Events
onmouseover/onmouseout - When the mouse passes over an element
onmousedown/onmouseup - When pressing/releasing a mouse button
onmousedown - When mouse is clicked: Alert which element
onmousedown - When mouse is clicked: Alert which button
onmousemove/onmouseout - When moving the mouse pointer over/out of an
image
onmouseover/onmouseout - When moving the mouse over/out of an image
onmouseover an image map
Click Events
Acting to the onclick event
onclick - When button is clicked
ondblclick - When a text is double-clicked
334
www.Sohrabpoor.com
Load Events
onload - When the page has been loaded
onload - When an image has been loaded
onerror - When an error occurs when loading an image
onunload - When the browser closes the document
onresize - When the browser window is resized
Others
What is the keycode of the key pressed?
What are the coordinates of the cursor?
What are the coordinates of the cursor, relative to the screen?
Was the shift key pressed?
Which event type occurred?
Examples explained
Window Object
Open a new window when clicking on a button
Open a new window and control its appearance
Blur and Focus a new window
Close the new window
Checks whether the new window has been closed or not
Write some text to the source (parent) window
Move the new window relative to its current position
Move the new window to the specified position
Print the current page
Resize a window by the specified pixels
Resize a window to a specified size
Scroll the content by the specified number of pixels
Scroll the content to a specified position
Window explained
335
www.Sohrabpoor.com
Screen Object
The visitor's screen: Width
The visitor's screen: Height
The visitor's screen: Available Width
The visitor's screen: Available Height
The visitor's screen: Color Depth
The visitor's screen: Pixel Depth
Screen explained
Location Object
Return the hostname and port of the current URL
Return the entire URL of the current page
Return the path name of the current URL
Return the protocol portion of the current URL
Load a new document
Replace the current document
Break out of a frame
Location explained
History Object
Display the number of URLs in the history list
Create a back button on a page
Create a forward button on a page
Load a specific URL from the history list
History explained
Navigator Object
Is cookies enabled in the visitor's browser?
What is the name of the visitor's browser?
What is the engine name of the visitor's browser?
What is the version information of the visitor's browser?
336
www.Sohrabpoor.com
Navigator explained
Popup Boxes
Display an alert box
Demonstrate line breaks in an alert box
Display a confirm box
Display a prompt box
Popup explained
Timing
Simple timing
Another simple timing
Timing event in an infinite loop
Timing event in an infinite loop - with a Stop button
A clock created with a timing event
Set and stop a timer with setInterval() and clearInterval()
Timing explained
Cookies
Create a welcome cookie
Cookies explained
337
www.Sohrabpoor.com
The Test
The test contains 25 questions and there is no time limit.
The test is not official, it's just a nice way to see how much you know, or
don't know, about JavaScript.
338
www.Sohrabpoor.com
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
String indexes are zero-based: The first character is in position 0, the second
in 1, and so on.
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
339
www.Sohrabpoor.com
String Properties
Property Description
String Methods
Method Description
concat() Joins two or more strings, and returns a new joined strings
340
www.Sohrabpoor.com
indexOf() Returns the position of the first found occurrence of a specified value in
a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in
a string
match() Searches a string for a match against a regular expression, and returns
the matches
341
www.Sohrabpoor.com
substring() Extracts the characters from a string, between two specified indices
All string methods return a new value. They do not change the original
variable.
These are not standard methods, and may not work as expected in all
browsers.
342
www.Sohrabpoor.com
Method Description
343
www.Sohrabpoor.com
Example
var x = 3.14; // A number with decimals
var y = 34; // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent)
notation:
Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
Number Properties
Property Description
344
www.Sohrabpoor.com
Number Methods
Method Description
toFixed(x) Formats a number with x numbers of digits after the decimal point
345
www.Sohrabpoor.com
All number methods return a new value. They do not change the original
variable.
346
www.Sohrabpoor.com
+= x += y x=x+y x = 15 Try it »
347
www.Sohrabpoor.com
*= x *= y x=x*y x = 50 Try it »
Given that text1 = "Good ", text2 = "Morning", and text3 = "", the
table below explains the operators:
348
www.Sohrabpoor.com
Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.
x == 5 true Try it »
=== equal value and equal type x === "5" false Try it »
!== not equal value or not equal type x !== "5" true Try it »
349
www.Sohrabpoor.com
variablename = (condition) ? value1:value2 voteable = (age < 18) ? "Too young":"Old enough"; Try it »
Example explained: 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".
Logical Operators
Logical operators are used to determine the logic between variables or
values.
Given that x = 6 and y = 3, the table below explains the logical operators:
350
www.Sohrabpoor.com
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-
bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
351
www.Sohrabpoor.com
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1, 2, 3, 4] // Returns object
typeof {name:'John', age:34} // Returns object
typeof new Date() // Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not
declared)
typeof null // Returns object
Try it Yourself »
Please observe:
You cannot use typeof to define if a JavaScript object is an array (or a date).
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];
Try it Yourself »
The delete operator deletes both the value of the property and the property
itself.
352
www.Sohrabpoor.com
After deletion, the property cannot be used before it is added back again.
The in Operator
The in operator returns true if the specified property is in the specified
object, otherwise false:
Example
// Arrays
var cars = ["Saab", "Volvo", "BMW"];
"Saab" in cars // Returns false (specify the index number instead
of value)
0 in cars // Returns true
1 in cars // Returns true
4 in cars // Returns false (does not exist)
"length" in cars // Returns true (length is an Array property)
// Objects
var person = {firstName:"John", lastName:"Doe", age:50};
"firstName" in person // Returns true
"age" in person // Returns true
// Predefined objects
"PI" in Math // Returns true
"NaN" in Number // Returns true
"length" in String // Returns true
Try it Yourself »
353
www.Sohrabpoor.com
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Example
<a href="javascript:void(0);">
Useless link
</a>
<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background color of body to red
</a>
Try it Yourself »
JavaScript Statements
In HTML, JavaScript statements are "instructions" to be "executed" by the
web browser.
This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":
354
www.Sohrabpoor.com
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
Statement Description
debugger Stops the execution of JavaScript, and calls (if available) the
debugging function
do ... while Executes a block of statements and repeats the block while a
condition is true
355
www.Sohrabpoor.com
try ... catch Marks the block of statements to be executed when an error
... finally occurs in a try block, and implements error handling
356
www.Sohrabpoor.com
Math is not a constructor. All properties/methods of Math can be called by using Math as an
object, without creating it.
Syntax
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
For a tutorial about the Math object, read our JavaScript Math Tutorial.
357
www.Sohrabpoor.com
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
358
www.Sohrabpoor.com
359
www.Sohrabpoor.com
For a tutorial about date and times, read our JavaScript Date Tutorial.
constructor Returns the function that created the Date object's prototype
360
www.Sohrabpoor.com
getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a
specified date
getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
361
www.Sohrabpoor.com
parse() Parses a date string and returns the number of milliseconds since January 1,
1970
setUTCDate() Sets the day of the month of a date object, according to universal time
362
www.Sohrabpoor.com
toDateString() Converts the date portion of a Date object into a readable string
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
363
www.Sohrabpoor.com
Array indexes are zero-based: The first element in the array is 0, the second
is 1, and so on.
Array Properties
Property Description
constructor Returns the function that created the Array object's prototype
364
www.Sohrabpoor.com
Array Methods
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specified positions
filter() Creates a new array with every element in an array that pass a test
find() Returns the value of the first element in an array that pass a test
findIndex() Returns the index of the first element in an array that pass a test
indexOf() Search the array for an element and returns its position
365
www.Sohrabpoor.com
lastIndexOf() Search the array for an element, starting at the end, and returns its position
map() Creates a new array with the result of calling a function for each array element
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
shift() Removes the first element of an array, and returns that element
366
www.Sohrabpoor.com
unshift() Adds new elements to the beginning of an array, and returns the new length
Example
Boolean(10 > 9) // returns true
Try it Yourself »
Or even easier:
Example
(10 > 9) // also returns true
10 > 9 // also returns true
Try it Yourself »
367
www.Sohrabpoor.com
Boolean Properties
Property Description
prototype Allows you to add properties and methods to the Boolean prototype
Boolean Methods
Method Description
Syntax
/pattern/modifiers;
Example
var patt = /w3schools/i
368
www.Sohrabpoor.com
Example explained:
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
Brackets
Brackets are used to find a range of characters:
Expression Description
369
www.Sohrabpoor.com
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
370
www.Sohrabpoor.com
Quantifiers
Quantifier Description
371
www.Sohrabpoor.com
constructor Returns the function that created the RegExp object's prototype
372
www.Sohrabpoor.com
373
www.Sohrabpoor.com
374
www.Sohrabpoor.com
Functions or Methods?
It makes sense to call the list above global functions rather than global
methods because the functions are called globally and not any objects.
Anyway, you can also call these functions methods, since they are methods
of the global object where they run. In a web browser, the global object is
the browser window. Then isNaN() is actually a window method:
window.isNaN().
375
www.Sohrabpoor.com
376
www.Sohrabpoor.com
Note: Values in quotes ("") indicate string values. Values in red indicate
values (some) programmers might not expect.
377
www.Sohrabpoor.com
For a tutorial about JavaScript Type Conversion, read our JavaScript Type
Conversion Tutorial.
Note: There is no public standard that applies to the Window object, but all
major browsers support it.
378
www.Sohrabpoor.com
379
www.Sohrabpoor.com
screen Returns the Screen object for the window (See Screen
object)
380
www.Sohrabpoor.com
381
www.Sohrabpoor.com
382
www.Sohrabpoor.com
Note: There is no public standard that applies to the navigator object, but all
major browsers support it.
383
www.Sohrabpoor.com
geolocation Returns a Geolocation object that can be used to locate the user's
position
userAgent Returns the user-agent header sent by the browser to the server
384
www.Sohrabpoor.com
taintEnabled() Removed in JavaScript version 1.2. Specifies whether the browser has
data tainting enabled
Note: There is no public standard that applies to the screen object, but all
major browsers support it.
availHeight Returns the height of the screen (excluding the Windows Taskbar)
availWidth Returns the width of the screen (excluding the Windows Taskbar)
colorDepth Returns the bit depth of the color palette for displaying images
385
www.Sohrabpoor.com
pixelDepth Returns the color resolution (in bits per pixel) of the screen
The history object is part of the window object and is accessed through the
window.history property.
Note: There is no public standard that applies to the history object, but all
major browsers support it.
386
www.Sohrabpoor.com
The location object is part of the window object and is accessed through the
window.location property.
Note: There is no public standard that applies to the location object, but all
major browsers support it.
387
www.Sohrabpoor.com
388
www.Sohrabpoor.com
The document object is the root node of the HTML document and the "owner"
of all other nodes:
(element nodes, text nodes, attribute nodes, and comment nodes).
The document object provides properties and methods to access all node
objects, from within JavaScript.
Tip: The document is a part of the Window object and can be accessed as
window.document.
Browser Support
Object
389
www.Sohrabpoor.com
390
www.Sohrabpoor.com
document.domain Returns the domain name of the server that loaded the
document
document.getElementById() Returns the element that has the ID attribute with the
specified value
391
www.Sohrabpoor.com
document.lastModified Returns the date and time the document was last
modified
392
www.Sohrabpoor.com
393
www.Sohrabpoor.com
Warning !!!
In the W3C DOM Core, the Document object inherits all properties and
methods from the Node object.
394
www.Sohrabpoor.com
Element objects can have child nodes of type element nodes, text nodes, or
comment nodes.
395
www.Sohrabpoor.com
Elements can also have attributes. Attributes are attribute nodes (See next
chapter).
Browser Support
Object
The Element Object and the NodeList Object are supported in all major
browsers.
396
www.Sohrabpoor.com
397
www.Sohrabpoor.com
398
www.Sohrabpoor.com
399
www.Sohrabpoor.com
element.nextSibling Returns the next node at the same node tree level
element.nextElementSibling Returns the next element at the same node tree level
element.normalize() Joins adjacent text nodes and removes empty text nodes
in an element
400
www.Sohrabpoor.com
element.previousSibling Returns the previous node at the same node tree level
element.previousElementSibling Returns the previous element at the same node tree level
401
www.Sohrabpoor.com
402
www.Sohrabpoor.com
403
www.Sohrabpoor.com
Browser Support
Object
The Attr Object and the NamedNodeMap Object is supported in all major
browsers.
404
www.Sohrabpoor.com
For future code quality, you should avoid using node object
properties and methods on attribute objects:
405
www.Sohrabpoor.com
406
www.Sohrabpoor.com
attr.ownerElement This is the HTML element you used to access the attribute
attr.parentNode This is the HTML element you used to access the attribute
407
www.Sohrabpoor.com
Events are normally used in combination with functions, and the function will
not be executed before the event occurs (such as when a user clicks a
button).
Tip: The event model was standardized by the W3C in DOM Level 2.
Mouse Events
Event Description DOM
oncontextmenu The event occurs when the user right-clicks on an element to open a 3
context menu
onmousedown The event occurs when the user presses a mouse button over an 2
element
onmouseenter The event occurs when the pointer is moved onto an element 2
408
www.Sohrabpoor.com
onmouseleave The event occurs when the pointer is moved out of an element 2
onmousemove The event occurs when the pointer is moving while it is over an 2
element
onmouseover The event occurs when the pointer is moved onto an element, or 2
onto one of its children
onmouseout The event occurs when a user moves the mouse pointer out of an 2
element, or out of one of its children
onmouseup The event occurs when a user releases a mouse button over an 2
element
Keyboard Events
Event Description DOM
409
www.Sohrabpoor.com
Frame/Object Events
Event Description DOM
onabort The event occurs when the loading of a resource has been aborted 2
onerror The event occurs when an error occurs while loading an external file 2
onhashchange The event occurs when there has been changes to the anchor part of a 3
URL
onpagehide The event occurs when the user navigates away from a webpage 3
onunload The event occurs once a page has unloaded (for <body>) 2
410
www.Sohrabpoor.com
Form Events
Event Description DOM
onchange The event occurs when the content of a form element, the selection, or the 2
checked state have changed (for <input>, <keygen>, <select>, and <textarea>)
onsearch The event occurs when the user writes something in a search field (for 3
<input="search">)
onselect The event occurs after the user selects some text (for <input> and <textarea>) 2
411
www.Sohrabpoor.com
Drag Events
Event Description DOM
ondragend The event occurs when the user has finished dragging an element 3
ondragenter The event occurs when the dragged element enters the drop target 3
ondragleave The event occurs when the dragged element leaves the drop target 3
ondragover The event occurs when the dragged element is over the drop target 3
ondragstart The event occurs when the user starts to drag an element 3
ondrop The event occurs when the dragged element is dropped on the drop target 3
Clipboard Events
Event Description DOM
oncopy The event occurs when the user copies the content of an element
oncut The event occurs when the user cuts the content of an element
onpaste The event occurs when the user pastes some content in an element
412
www.Sohrabpoor.com
Print Events
Event Description DOM
onafterprint The event occurs when a page has started printing, or if the print dialogue 3
box has been closed
Media Events
Event Description DOM
oncanplay The event occurs when the browser can start playing the media (when 3
it has buffered enough to begin)
oncanplaythrough The event occurs when the browser can play through the media 3
without stopping for buffering
ondurationchange The event occurs when the duration of the media is changed 3
onemptied The event occurs when something bad happens and the media file is 3
suddenly unavailable (like unexpectedly disconnects)
onended The event occurs when the media has reach the end (useful for 3
messages like "thanks for listening")
413
www.Sohrabpoor.com
onerror The event occurs when an error occurred during the loading of a 3
media file
onloadedmetadata The event occurs when meta data (like dimensions and duration) are 3
loaded
onloadstart The event occurs when the browser starts looking for the specified 3
media
onpause The event occurs when the media is paused either by the user or 3
programmatically
onplay The event occurs when the media has been started or is no longer 3
paused
onplaying The event occurs when the media is playing after having been paused 3
or stopped for buffering
onprogress The event occurs when the browser is in the process of getting the 3
media data (downloading the media)
onratechange The event occurs when the playing speed of the media is changed 3
onseeked The event occurs when the user is finished moving/skipping to a new 3
position in the media
onseeking The event occurs when the user starts moving/skipping to a new 3
position in the media
414
www.Sohrabpoor.com
onstalled The event occurs when the browser is trying to get media data, but 3
data is not available
onsuspend The event occurs when the browser is intentionally not getting media 3
data
ontimeupdate The event occurs when the playing position has changed (like when 3
the user fast forwards to a different point in the media)
onvolumechange The event occurs when the volume of the media has changed 3
(includes setting the volume to "mute")
onwaiting The event occurs when the media has paused but is expected to 3
resume (like when the media pauses to buffer more data)
Animation Events
Event Description DOM
415
www.Sohrabpoor.com
Transition Events
Event Description DOM
Server-Sent Events
Event Description DOM
onerror The event occurs when an error occurs with the event source
onmessage The event occurs when a message is received through the event source
onopen The event occurs when a connection with the event source is opened
Misc Events
Event Description DOM
onmessage The event occurs when a message is received through or from an object 3
(WebSocket, Web Worker, Event Source or a child frame or a parent window)
ononline The event occurs when the browser starts to work online 3
416
www.Sohrabpoor.com
onoffline The event occurs when the browser starts to work offline 3
onshow The event occurs when a <menu> element is shown as a context menu 3
ontoggle The event occurs when the user opens or closes the <details> element 3
onwheel The event occurs when the mouse wheel rolls up or down over an element 3
Touch Events
Event Description DOM
ontouchend The event occurs when a finger is removed from a touch screen
ontouchmove The event occurs when a finger is dragged across the screen
Event Object
Constants
417
www.Sohrabpoor.com
AT_TARGET The current event is in the target phase, i.e. it is being evaluated at the 2
event target (2)
Properties
cancelable Returns whether or not an event can have its default action prevented 2
currentTarget Returns the element whose event listeners triggered the event 2
defaultPrevented Returns whether or not the preventDefault() method was called for the 3
event
eventPhase Returns which phase of the event flow is currently being evaluated 2
418
www.Sohrabpoor.com
timeStamp Returns the time (in milliseconds relative to the epoch) at which the 2
event was created
view Returns a reference to the Window object where the event occured 2
Methods
preventDefault() Cancels the event if it is cancelable, meaning that the default action 2
that belongs to the event will not occur
stopImmediatePropagation() Prevents other listeners of the same event from being called 3
MouseEvent Object
Property Description DOM
altKey Returns whether the "ALT" key was pressed when the mouse event was triggered 2
button Returns which mouse button was pressed when the mouse event was triggered 2
419
www.Sohrabpoor.com
buttons Returns which mouse buttons were pressed when the mouse event was triggered 3
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current 2
window, when the mouse event was triggered
clientY Returns the vertical coordinate of the mouse pointer, relative to the current 2
window, when the mouse event was triggered
ctrlKey Returns whether the "CTRL" key was pressed when the mouse event was triggered 2
detail Returns a number that indicates how many times the mouse was clicked 2
metaKey Returns whether the "META" key was pressed when an event was triggered 2
pageX Returns the horizontal coordinate of the mouse pointer, relative to the document,
when the mouse event was triggered
pageY Returns the vertical coordinate of the mouse pointer, relative to the document,
when the mouse event was triggered
relatedTarget Returns the element related to the element that triggered the mouse event 2
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, 2
when an event was triggered
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when 2
an event was triggered
shiftKey Returns whether the "SHIFT" key was pressed when an event was triggered 2
420
www.Sohrabpoor.com
which Returns which mouse button was pressed when the mouse event was triggered 2
KeyboardEvent Object
Property Description DOM
altKey Returns whether the "ALT" key was pressed when the key event was triggered 2
ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered 2
charCode Returns the Unicode character code of the key that triggered the onkeypress event 2
key Returns the key value of the key represented by the event 3
keyCode Returns the Unicode character code of the key that triggered the onkeypress event, 2
or the Unicode key code of the key that triggered the onkeydown or onkeyup event
metaKey Returns whether the "meta" key was pressed when the key event was triggered 2
shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered 2
which Returns the Unicode character code of the key that triggered the onkeypress event, 2
or the Unicode key code of the key that triggered the onkeydown or onkeyup event
421
www.Sohrabpoor.com
HashChangeEvent Object
Property Description DOM
newURL Returns the URL of the document, after the hash has been changed
oldURL Returns the URL of the document, before the hash was changed
PageTransitionEvent Object
Property Description DOM
FocusEvent Object
Property Description DOM
relatedTarget Returns the element related to the element that triggered the event 3
AnimationEvent Object
Property Description DOM
422
www.Sohrabpoor.com
TransitionEvent Object
Property Description DOM
propertyName Returns the name of the CSS property associated with the transition
WheelEvent Object
Property Description DOM
deltaZ Returns the scroll amount of a mouse wheel for the z-axis 3
deltaMode Returns a number that represents the unit of measurements for delta values 3
(pixels, lines or pages)
423
www.Sohrabpoor.com
Example
var x = document.getElementsByTagName("STYLE");
Try it Yourself »
Example
var x = document.getElementById("myH1").style;
Try it Yourself »
Example
var x = document.createElement("STYLE");
Try it Yourself »
Example
document.getElementById("myH1").style.color = "red";
Try it Yourself »
424
www.Sohrabpoor.com
alignContent Sets or returns the alignment between the lines inside a flexible 3
container when the items do not use all available space
alignItems Sets or returns the alignment for items inside a flexible container 3
alignSelf Sets or returns the alignment for selected items inside a flexible 3
container
animation A shorthand property for all the animation properties below, except 3
the animationPlayState property
animationDirection Sets or returns whether or not the animation should play in reverse 3
on alternate cycles
animationFillMode Sets or returns what values are applied by the animation outside the 3
time it is executing
425
www.Sohrabpoor.com
backfaceVisibility Sets or returns whether or not an element should be visible when not 3
facing the screen
426
www.Sohrabpoor.com
borderBottomLeftRadius Sets or returns the shape of the border of the bottom-left corner 3
borderBottomRightRadius Sets or returns the shape of the border of the bottom-right corner 3
borderCollapse Sets or returns whether the table border should be collapsed into a 2
single border, or not
borderColor Sets or returns the color of an element's border (can have up to four 1
values)
borderImageOutset Sets or returns the amount by which the border image area extends 3
beyond the border box
427
www.Sohrabpoor.com
borderStyle Sets or returns the style of an element's border (can have up to four 1
values)
428
www.Sohrabpoor.com
borderTopLeftRadius Sets or returns the shape of the border of the top-left corner 3
borderTopRightRadius Sets or returns the shape of the border of the top-right corner 3
borderWidth Sets or returns the width of an element's border (can have up to four 1
values)
boxSizing Allows you to define certain elements to fit an area in a certain way 3
clear Sets or returns the position of the element relative to floating objects 1
429
www.Sohrabpoor.com
columnSpan Sets or returns how many columns an element should span across 3
430
www.Sohrabpoor.com
cursor Sets or returns the type of cursor to display for the mouse pointer 2
emptyCells Sets or returns whether to show the border and background of empty 2
cells, or not
filter Sets or returns image filters (visual effects, like blur and saturation) 3
flex Sets or returns the length of the item, relative to the rest 3
431
www.Sohrabpoor.com
flexGrow Sets or returns how much the item will grow relative to the rest 3
flexShrink Sets or returns how the item will shrink relative to the rest 3
flexWrap Sets or returns whether the flexible items should wrap or not 3
fontStyle Sets or returns whether the style of the font is normal, italic or 1
oblique
fontVariant Sets or returns whether the font should be displayed in small capital 1
letters
432
www.Sohrabpoor.com
icon Provides the author the ability to style an element with an iconic 3
equivalent
justifyContent Sets or returns the alignment between the items inside a flexible 3
container when the items do not use all available space.
433
www.Sohrabpoor.com
434
www.Sohrabpoor.com
order Sets or returns the order of the flexible item, relative to the rest 3
orphans Sets or returns the minimum number of lines for an element that 2
must be left at the bottom of a page when a page break occurs inside
an element
overflow Sets or returns what to do with content that renders outside the 2
element box
435
www.Sohrabpoor.com
436
www.Sohrabpoor.com
position Sets or returns the type of positioning method used for an element 2
(static, relative, absolute or fixed)
quotes Sets or returns the type of quotation marks for embedded quotations 2
tableLayout Sets or returns the way to lay out table cells, rows, and columns 2
textAlignLast Sets or returns how the last line of a block or a line right before a 3
forced line break is aligned when text-align is "justify"
437
www.Sohrabpoor.com
textOverflow Sets or returns what should happen when text overflows the 3
containing element
transitionProperty Sets or returns the CSS property that the transition effect is for 3
438
www.Sohrabpoor.com
whiteSpace Sets or returns how to handle tabs, line breaks and whitespace in a 1
text
wordWrap Allows long, unbreakable words to be broken and wrap to the next 3
line
widows Sets or returns the minimum number of lines for an element that 2
must be visible at the top of a page
439
www.Sohrabpoor.com
Example
var x = document.getElementById("myAnchor");
Try it Yourself »
Example
var x = document.createElement("A");
Try it Yourself »
Property Description
hash Sets or returns the anchor part of the href attribute value
440
www.Sohrabpoor.com
host Sets or returns the hostname and port part of the href attribute value
hostname Sets or returns the hostname part of the href attribute value
origin Returns the protocol, hostname and port part of the href attribute value
password Sets or returns the password part of the href attribute value
pathname Sets or returns the pathname part of the href attribute value
port Sets or returns the port part of the href attribute value
protocol Sets or returns the protocol part of the href attribute value
search Sets or returns the querystring part of the href attribute value
441
www.Sohrabpoor.com
username Sets or returns the username part of the href attribute value
Related Pages
HTML tutorial: HTML links
Example
var x = document.getElementById("myAbbr");
Try it Yourself »
442
www.Sohrabpoor.com
Example
var x = document.createElement("ABBR");
Try it Yourself »
Related Pages
HTML reference: HTML <abbr> tag
Example
var x = document.getElementById("myAdr");
Try it Yourself »
443
www.Sohrabpoor.com
Example
var x = document.createElement("ADDRESS");
Try it Yourself »
Related Pages
HTML reference: HTML <address> tag
Example
var x = document.getElementById("myArea");
Try it Yourself »
Example
var x = document.createElement("AREA");
Try it Yourself »
444
www.Sohrabpoor.com
hash Sets or returns the anchor part of the href attribute value
host Sets or returns the hostname and port part of the href attribute value
hostname Sets or returns the hostname part of the href attribute value
origin Returns the protocol, hostname and port part of the href attribute value
password Sets or returns the password part of the href attribute value
pathname Sets or returns the pathname part of the href attribute value
port Sets or returns the port part of the href attribute value
445
www.Sohrabpoor.com
protocol Sets or returns the protocol part of the href attribute value
search Sets or returns the querystring part of the href attribute value
username Sets or returns the username part of the href attribute value
Related Pages
HTML reference: HTML <area> tag
446
www.Sohrabpoor.com
Example
var x = document.getElementById("myArticle");
Try it Yourself »
Example
var x = document.createElement("ARTICLE");
Try it Yourself »
Related Pages
HTML reference: HTML <article> tag
Aside Object
The Aside Object is new in HTML5.
447
www.Sohrabpoor.com
Example
var x = document.getElementById("myAside");
Try it Yourself »
Example
var x = document.createElement("ASIDE");
Try it Yourself »
Related Pages
HTML reference: HTML <aside> tag
Audio Object
The Audio Object is new in HTML5.
448
www.Sohrabpoor.com
Example
var x = document.getElementById("myAudio");
Try it Yourself »
Example
var x = document.createElement("AUDIO");
Try it Yourself »
autoplay Sets or returns whether the audio should start playing as soon as it is ready
449
www.Sohrabpoor.com
currentTime Sets or returns the current playback position in an audio (in seconds)
defaultPlaybackRate Sets or returns whether the default playback speed of the audio
error Returns a MediaError object representing the error state of the audio
loop Sets or returns whether the audio should start playing over again, every
time it is finished
mediaGroup Sets or returns the name of the media group the audio(s) is a part of
450
www.Sohrabpoor.com
played Returns a TimeRanges object representing the played parts of the audio
451
www.Sohrabpoor.com
canPlayType() Checks whether the browser can play the specified audio type
getStartDate() Returns a new Date object, representing the current timeline offset
Bold Object
The Bold object represents an HTML <b> element.
452
www.Sohrabpoor.com
Example
var x = document.getElementById("myB");
Try it Yourself »
Example
var x = document.createElement("B");
Try it Yourself »
Related Pages
HTML tutorial: HTML Text Formatting Elements
Example
var x = document.getElementById("myBase");
Try it Yourself »
Example
var x = document.createElement("BASE");
Try it Yourself »
href Sets or returns the value of the href attribute in a base element
target Sets or returns the value of the target attribute in a base element
454
www.Sohrabpoor.com
Example
var x = document.getElementById("myBdo");
Try it Yourself »
Example
var x = document.createElement("BDO");
Try it Yourself »
455
www.Sohrabpoor.com
Example
var x = document.getElementById("myBlockquote");
Try it Yourself »
Example
var x = document.createElement("BLOCKQUOTE");
Try it Yourself »
456
www.Sohrabpoor.com
Example
var x = document.getElementsByTagName("BODY")[0];
Try it Yourself »
var x = document.createElement("BODY");
457
www.Sohrabpoor.com
Access a BR Object
You can access a <br> element by using getElementById():
Example
var x = document.getElementById("myBR");
Try it Yourself »
458
www.Sohrabpoor.com
Create a BR Object
You can create a <br> element by using the document.createElement()
method:
Example
var x = document.createElement("BR");
Try it Yourself »
BR Object Properties
Property Description
Example
var x = document.getElementById("myBtn");
Try it Yourself »
459
www.Sohrabpoor.com
Example
var x = document.createElement("BUTTON");
Try it Yourself »
Property Description
autofocus Sets or returns whether a button should automatically get focus when the
page loads, or not
460
www.Sohrabpoor.com
The HTML5 <canvas> tag is used to draw graphics, on the fly, with
JavaScript.
Example
var x = document.getElementById("myCanvas");
Try it Yourself »
461
www.Sohrabpoor.com
Example
var x = document.createElement("CANVAS");
Try it Yourself »
Note: The <canvas> element has no drawing abilities of its own (it is only a
container for graphics) - you must use a script to actually draw the graphics.
This reference will cover the properties and methods of the getContext("2d")
object, which can be used to draw text, lines, boxes, circles, and more - on
the canvas.
fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing
strokeStyle Sets or returns the color, gradient, or pattern used for strokes
shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape
shadowOffsetY Sets or returns the vertical distance of the shadow from the shape
462
www.Sohrabpoor.com
Method Description
Line Styles
Property Description
lineCap Sets or returns the style of the end caps for a line
lineJoin Sets or returns the type of corner created, when two lines meet
463
www.Sohrabpoor.com
Rectangles
Method Description
Paths
Method Description
moveTo() Moves the path to the specified point in the canvas, without creating
a line
closePath() Creates a path from the current point back to the starting point
464
www.Sohrabpoor.com
lineTo() Adds a new point and creates a line from that point to the last
specified point in the canvas
clip() Clips a region of any shape and size from the original canvas
isPointInPath() Returns true if the specified point is in the current path, otherwise
false
Transformations
Method Description
465
www.Sohrabpoor.com
Text
Property Description
font Sets or returns the current font properties for text content
textBaseline Sets or returns the current text baseline used when drawing text
Method Description
measureText() Returns an object that contains the width of the specified text
466
www.Sohrabpoor.com
Image Drawing
Method Description
Pixel Manipulation
Property Description
data Returns an object that contains image data of a specified ImageData object
Method Description
getImageData() Returns an ImageData object that copies the pixel data for the specified
rectangle on a canvas
putImageData() Puts the image data (from a specified ImageData object) back onto the
canvas
467
www.Sohrabpoor.com
Compositing
Property Description
globalCompositeOperation Sets or returns how a new image are drawn onto an existing image
Other
Method Description
createEvent()
getContext()
toDataURL()
468
www.Sohrabpoor.com
Example
var x = document.getElementById("myCaption");
Try it Yourself »
Example
var x = document.createElement("CAPTION");
Try it Yourself »
469
www.Sohrabpoor.com
Example
var x = document.getElementById("myCite");
Try it Yourself »
Example
var x = document.createElement("CITE");
Try it Yourself »
Example
var x = document.getElementById("myCode");
Try it Yourself »
Example
var x = document.createElement("CODE");
Try it Yourself »
Example
var x = document.getElementById("myCol");
Try it Yourself »
var x = document.createElement("COL");
471
www.Sohrabpoor.com
Example
var x = document.getElementById("myColgroup");
Try it Yourself »
472
www.Sohrabpoor.com
span Sets or returns the value of the span attribute of a column group
Example
var x = document.getElementById("myDatalist");
Try it Yourself »
473
www.Sohrabpoor.com
Example
var x = document.createElement("DATALIST");
Try it Yourself »
Access a DD Object
You can access a <dd> element by using getElementById():
Example
var x = document.getElementById("myDD");
Try it Yourself »
Create a DD Object
You can create a <dd> element by using the document.createElement()
method:
474
www.Sohrabpoor.com
Example
var x = document.createElement("DD");
Try it Yourself »
Example
var x = document.getElementById("myDel");
Try it Yourself »
Example
var x = document.createElement("DEL");
Try it Yourself »
475
www.Sohrabpoor.com
cite Sets or returns the value of the cite attribute of a deleted text
dateTime Sets or returns the value of the datetime attribute of a deleted text
Example
var x = document.getElementById("myDetails");
Try it Yourself »
476
www.Sohrabpoor.com
Example
var x = document.createElement("DETAILS");
Try it Yourself »
Example
var x = document.getElementById("myDFN");
Try it Yourself »
477
www.Sohrabpoor.com
Example
var x = document.createElement("DFN");
Try it Yourself »
Example
var x = document.getElementById("myDialog");
Try it Yourself »
Example
var x = document.createElement("DIALOG");
Try it Yourself »
478
www.Sohrabpoor.com
showModal() Shows the dialog and makes it the top-most modal dialog
479
www.Sohrabpoor.com
Example
var x = document.getElementById("myDIV");
Try it Yourself »
Example
var x = document.createElement("DIV");
Try it Yourself »
480
www.Sohrabpoor.com
Example
var x = document.getElementById("myDL");
Try it Yourself »
Example
var x = document.createElement("DL");
Try it Yourself »
Access a DT Object
You can access a <dt> element by using getElementById():
481
www.Sohrabpoor.com
Example
var x = document.getElementById("myDT");
Try it Yourself »
Create a DT Object
You can create a <dt> element by using the document.createElement()
method:
Example
var x = document.createElement("DT");
Try it Yourself »
Example
var x = document.getElementById("myEm");
Try it Yourself »
482
www.Sohrabpoor.com
Example
var x = document.createElement("EM");
Try it Yourself »
Example
var x = document.getElementById("myEmbed");
Try it Yourself »
Example
var x = document.createElement("EMBED");
Try it Yourself »
483
www.Sohrabpoor.com
height Sets or returns the value of the height attribute in an embed element
src Sets or returns the value of the src attribute in an embed element
type Sets or returns the value of the type attribute in an embed element
width Sets or returns the value of the width attribute in an embed element
Example
var x = document.getElementById("myFieldset");
Try it Yourself »
484
www.Sohrabpoor.com
Example
var x = document.createElement("FIELDSET");
Try it Yourself »
Property Description
485
www.Sohrabpoor.com
Example
var x = document.getElementById("myFigCap");
Try it Yourself »
Example
var x = document.createElement("FIGCAPTION");
Try it Yourself »
486
www.Sohrabpoor.com
Example
var x = document.getElementById("myFigure");
Try it Yourself »
Example
var x = document.createElement("FIGURE");
Try it Yourself »
Footer Object
The Footer Object is new in HTML5.
487
www.Sohrabpoor.com
Example
var x = document.getElementById("myFooter");
Try it Yourself »
Example
var x = document.createElement("FOOTER");
Try it Yourself »
Example
var x = document.getElementById("myForm");
Try it Yourself »
Tip: You can also access a <form> element by using the forms collection.
488
www.Sohrabpoor.com
Example
var x = document.createElement("FORM");
Try it Yourself »
Property Description
489
www.Sohrabpoor.com
noValidate Sets or returns whether the form-data should be validated or not, on submission
var x = document.getElementsByTagName("HEAD")[0];
490
www.Sohrabpoor.com
var x = document.createElement("HEAD");
Example
var x = document.getElementById("myHeader");
Try it Yourself »
Example
var x = document.createElement("HEADER");
Try it Yourself »
491
www.Sohrabpoor.com
Related Pages
HTML tutorial: HTML5 Semantic Elements
Example
var x = document.getElementById("myHeading");
Try it Yourself »
Example
var x = document.createElement("H1");
Try it Yourself »
492
www.Sohrabpoor.com
Access a HR Object
You can access a <hr> element by using getElementById():
Example
var x = document.getElementById("myHR");
Try it Yourself »
Create a HR Object
You can create a <hr> element by using the document.createElement()
method:
Example
var x = document.createElement("HR");
Try it Yourself »
493
www.Sohrabpoor.com
HR Object Properties
Property Description
494
www.Sohrabpoor.com
Example
var x = document.getElementsByTagName("HTML")[0];
Try it Yourself »
Related Pages
HTML tutorial: HTML Introduction
Example
var x = document.getElementById("myItalic");
Try it Yourself »
495
www.Sohrabpoor.com
Example
var x = document.createElement("I");
Try it Yourself »
Related Pages
HTML tutorial: HTML Text Formatting Elements
Example
var x = document.getElementById("myFrame");
Try it Yourself »
496
www.Sohrabpoor.com
Example
var x = document.createElement("IFRAME");
Try it Yourself »
Property Description
497
www.Sohrabpoor.com
498
www.Sohrabpoor.com
Example
var x = document.getElementById("myImg");
Try it Yourself »
Tip: You can also access an <img> element by using the images collection.
Example
var x = document.createElement("IMG");
Try it Yourself »
499
www.Sohrabpoor.com
500
www.Sohrabpoor.com
Example
var x = document.getElementById("myIns");
Try it Yourself »
Example
var x = document.createElement("INS");
Try it Yourself »
501
www.Sohrabpoor.com
cite Sets or returns the value of the cite attribute of an inserted text
dateTime Sets or returns the value of the datetime attribute of an inserted text
Example
var x = document.getElementById("myBtn");
Try it Yourself »
502
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
Try it Yourself »
Property Description
autofocus Sets or returns whether an input button should automatically get focus when
the page loads
form Returns a reference to the form that contains the input button
name Sets or returns the value of the name attribute of an input button
value Sets or returns the value of the value attribute of an input button
503
www.Sohrabpoor.com
Example
var x = document.getElementById("myCheck");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
Try it Yourself »
504
www.Sohrabpoor.com
Property Description
autofocus Sets or returns whether a checkbox should automatically get focus when the
page loads
required Sets or returns whether the checkbox must be checked before submitting a
form
505
www.Sohrabpoor.com
Example
var x = document.getElementById("myColor");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "color");
Try it Yourself »
506
www.Sohrabpoor.com
autocomplete Sets or returns the value of the autocomplete attribute of a color picker
autofocus Sets or returns whether a color picker should automatically get focus when the
page loads
form Returns a reference to the form that contains the color picker
list Returns a reference to the <datalist> element that contains the color picker
name Sets or returns the value of the name attribute of a color picker
value Sets or returns the value of the value attribute of a color picker
507
www.Sohrabpoor.com
The Input Date object represents an HTML <input> element with type="date".
Note: <input> elements with type="date" do not show as any date field/calendar in Firefox.
Example
var x = document.getElementById("myDate");
Try it Yourself »
Tip: You can also access <input type="date"> by searching through the elements collection
of a form.
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "date");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a date field
508
www.Sohrabpoor.com
autofocus Sets or returns whether a date field should automatically get focus when the
page loads
form Returns a reference to the form that contains the date field
list Returns a reference to the datalist that contains the date field
max Sets or returns the value of the max attribute of the date field
min Sets or returns the value of the min attribute of the date field
name Sets or returns the value of the name attribute of a date field
required Sets or returns whether the date field must be filled out before submitting a
form
step Sets or returns the value of the step attribute of the date field
value Sets or returns the value of the value attribute of a date field
509
www.Sohrabpoor.com
Example
var x = document.getElementById("myDatetime");
Try it Yourself »
510
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "datetime");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a datetime field
autofocus Sets or returns whether a datetime field should automatically get focus when
the page loads
form Returns a reference to the form that contains the datetime field
list Returns a reference to the datalist that contains the datetime field
max Sets or returns the value of the max attribute of the datetime field
min Sets or returns the value of the min attribute of the datetime field
511
www.Sohrabpoor.com
name Sets or returns the value of the name attribute of a datetime field
required Sets or returns whether the datetime field must be filled out before
submitting a form
step Sets or returns the value of the step attribute of the datetime field
value Sets or returns the value of the value attribute of a datetime field
512
www.Sohrabpoor.com
Example
var x = document.getElementById("myLocalDate");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "datetime-local");
Try it Yourself »
513
www.Sohrabpoor.com
autocomplete Sets or returns the value of the autocomplete attribute of a local datetime field
autofocus Sets or returns whether a local datetime field should automatically get focus
upon page load
form Returns a reference to the form that contains the local datetime field
list Returns a reference to the datalist that contains the local datetime field
max Sets or returns the value of the max attribute of the local datetime field
min Sets or returns the value of the min attribute of the local datetime field
name Sets or returns the value of the name attribute of a local datetime field
readOnly Sets or returns whether the local datetime field is read-only, or not
required Sets or returns whether the local datetime field must be filled out before
submitting a form
514
www.Sohrabpoor.com
step Sets or returns the value of the step attribute of the local datetime field
type Returns which type of form element the local datetime field is
value Sets or returns the value of the value attribute of a local datetime field
515
www.Sohrabpoor.com
Example
var x = document.getElementById("myEmail");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "email");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of an email field
autofocus Sets or returns whether an email field should automatically get focus when
the page loads
516
www.Sohrabpoor.com
form Returns a reference to the form that contains the email field
list Returns a reference to the datalist that contains the email field
maxLength Sets or returns the value of the maxlength attribute of an email field
multiple Sets or returns whether a user is allowed to enter more than one email
address in the email field
name Sets or returns the value of the name attribute of an email field
pattern Sets or returns the value of the pattern attribute of an email field
placeholder Sets or returns the value of the placeholder attribute of an email field
required Sets or returns whether the email field must be filled out before submitting a
form
size Sets or returns the value of the size attribute of the email field
value Sets or returns the value of the value attribute of an email field
517
www.Sohrabpoor.com
Example
var x = document.getElementById("myFile");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
Try it Yourself »
518
www.Sohrabpoor.com
Property Description
accept Sets or returns the value of the accept attribute of the file upload button
autofocus Sets or returns whether a file upload button should automatically get focus upon
page load
defaultValue Sets or returns the default value of the file upload button
disabled Sets or returns whether the file upload button is disabled, or not
files Returns a FileList object that represents the file or files selected with the file
upload button
form Returns a reference to the form that contains the file upload button
multiple Sets or returns whether a user is allowed to select more than one file in the file
upload field
name Sets or returns the value of the name attribute of the file upload button
required Sets or returns whether a file in the file upload field must be selected before
submitting a form
type Returns which type of form element the file upload button is
519
www.Sohrabpoor.com
Example
var x = document.getElementById("myInput");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "hidden");
Try it Yourself »
520
www.Sohrabpoor.com
Property Description
defaultValue Sets or returns the default value of the hidden input field
form Returns a reference to the form that contains the hidden input field
name Sets or returns the value of the name attribute of the hidden input field
value Sets or returns the value of the value attribute of the hidden input field
var x = document.getElementById("myImage");
521
www.Sohrabpoor.com
var x = document.createElement("INPUT");
x.setAttribute("type", "image");
Property Description
alt Sets or returns the value of the alt attribute of an input image
autofocus Sets or returns whether an input image should automatically get focus when
the page loads
form Returns a reference to the form that contains the input image
formAction Sets or returns the value of the formaction attribute of an input image
formEnctype Sets or returns the value of the formenctype attribute of an input image
formMethod Sets or returns the value of the formmethod attribute of an input image
522
www.Sohrabpoor.com
formTarget Sets or returns the value of the formtarget attribute an input image
height Sets or returns the value of the height attribute of the input image
name Sets or returns the value of the name attribute of an input image
src Sets or returns the value of the src attribute of the input image
value Sets or returns the value of the value attribute of an input image
width Sets or returns the value of the width attribute of the input image
523
www.Sohrabpoor.com
Example
var x = document.getElementById("myMonth");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "month");
Try it Yourself »
524
www.Sohrabpoor.com
autocomplete Sets or returns the value of the autocomplete attribute of a month field
autofocus Sets or returns whether a month field should automatically get focus when
the page loads
form Returns a reference to the form that contains the month field
list Returns a reference to the datalist that contains the month field
max Sets or returns the value of the max attribute of the month field
min Sets or returns the value of the min attribute of the month field
name Sets or returns the value of the name attribute of a month field
required Sets or returns whether the month field must be filled out before submitting
a form
525
www.Sohrabpoor.com
step Sets or returns the value of the step attribute of the month field
value Sets or returns the value of the value attribute of a month field
526
www.Sohrabpoor.com
Example
var x = document.getElementById("myNumber");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "number");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a number field
autofocus Sets or returns whether a number field should automatically get focus when
the page loads
527
www.Sohrabpoor.com
form Returns a reference to the form that contains the number field
list Returns a reference to the datalist that contains the number field
max Sets or returns the value of the max attribute of a number field
min Sets or returns the value of the min attribute of a number field
name Sets or returns the value of the name attribute of a number field
placeholder Sets or returns the value of the placeholder attribute of a number field
required Sets or returns whether the number field must be filled out before submitting
a form
step Sets or returns the value of the step attribute of a number field
value Sets or returns the value of the value attribute of a number field
528
www.Sohrabpoor.com
Example
var x = document.getElementById("myPsw");
Try it Yourself »
529
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "password");
Try it Yourself »
Property Description
autocomplete Sets or returns the value of the autocomplete attribute of a password field
autofocus Sets or returns whether a password field should automatically get focus when
the page loads
form Returns a reference to the form that contains the password field
maxLength Sets or returns the value of the maxlength attribute of a password field
name Sets or returns the value of the name attribute of a password field
530
www.Sohrabpoor.com
pattern Sets or returns the value of the pattern attribute of a password field
placeholder Sets or returns the value of the placeholder attribute of a password field
required Sets or returns whether the password field must be filled out before
submitting a form
size Sets or returns the value of the size attribute of a password field
value Sets or returns the value of the value attribute of the password field
531
www.Sohrabpoor.com
Example
var x = document.getElementById("myRadio");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "radio");
Try it Yourself »
Property Description
autofocus Sets or returns whether a radio button should automatically get focus when the
page loads
532
www.Sohrabpoor.com
form Returns a reference to the form that contains the radio button
name Sets or returns the value of the name attribute of a radio button
required Sets or returns whether the radio button must be checked before submitting a
form
value Sets or returns the value of the value attribute of the radio button
533
www.Sohrabpoor.com
The Input Range object represents an HTML <input> element with type="range".
Note: <input> elements with type="range" are not supported in Internet Explorer 9 and
earlier versions.
Example
var x = document.getElementById("myRange");
Try it Yourself »
Tip: You can also access <input type="range"> by searching through the elements collection
of a form.
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "range");
Try it Yourself »
534
www.Sohrabpoor.com
autocomplete Sets or returns the value of the autocomplete attribute of a slider control
autofocus Sets or returns whether a slider control should automatically get focus when
the page loads
form Returns a reference to the form that contains the slider control
list Returns a reference to the datalist that contains the slider control
max Sets or returns the value of the max attribute of the slider control
min Sets or returns the value of the min attribute of the slider control
name Sets or returns the value of the name attribute of a slider control
step Sets or returns the value of the step attribute of the slider control
535
www.Sohrabpoor.com
value Sets or returns the value of the value attribute of a slider control
Example
var x = document.getElementById("myReset");
Try it Yourself »
536
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "reset");
Try it Yourself »
Property Description
autofocus Sets or returns whether a reset button should automatically get focus when the
page loads
form Returns a reference to the form that contains the reset button
name Sets or returns the value of the name attribute of a reset button
value Sets or returns the value of the value attribute of the reset button
537
www.Sohrabpoor.com
The Input Search object represents an HTML <input> element with type="search".
Example
var x = document.getElementById("mySearch");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "search");
Try it Yourself »
538
www.Sohrabpoor.com
autocomplete Sets or returns the value of the autocomplete attribute of a search field
autofocus Sets or returns whether a search field should automatically get focus when the
page loads
form Returns a reference to the form that contains the search field
list Returns a reference to the datalist that contains the search field
maxLength Sets or returns the value of the maxlength attribute of a search field
name Sets or returns the value of the name attribute of a search field
pattern Sets or returns the value of the pattern attribute of a search field
placeholder Sets or returns the value of the placeholder attribute of a search field
539
www.Sohrabpoor.com
required Sets or returns whether the search field must be filled out before submitting a
form
size Sets or returns the value of the size attribute of the search field
value Sets or returns the value of the value attribute of a search field
Example
var x = document.getElementById("mySubmit");
Try it Yourself »
540
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "submit");
Try it Yourself »
Property Description
autofocus Sets or returns whether a submit button should automatically get focus when
the page loads
form Returns a reference to the form that contains the submit button
formAction Sets or returns the value of the formaction attribute of a submit button
formEnctype Sets or returns the value of the formenctype attribute of a submit button
formMethod Sets or returns the value of the formmethod attribute of a submit button
541
www.Sohrabpoor.com
formTarget Sets or returns the value of the formtarget attribute of a submit button
name Sets or returns the value of the name attribute of a submit button
value Sets or returns the value of the value attribute of the submit button
Example
var x = document.getElementById("myText");
Try it Yourself »
542
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
Try it Yourself »
Property Description
autocomplete Sets or returns the value of the autocomplete attribute of a text field
autofocus Sets or returns whether a text field should automatically get focus when the
page loads
form Returns a reference to the form that contains the text field
list Returns a reference to the datalist that contains the text field
maxLength Sets or returns the value of the maxlength attribute of a text field
543
www.Sohrabpoor.com
name Sets or returns the value of the name attribute of a text field
pattern Sets or returns the value of the pattern attribute of a text field
placeholder Sets or returns the value of the placeholder attribute of a text field
required Sets or returns whether the text field must be filled out before submitting a
form
size Sets or returns the value of the size attribute of a text field
value Sets or returns the value of the value attribute of the text field
The Input Time object represents an HTML <input> element with type="time".
Note: <input> elements with type="time" do not show as any time field in Firefox.
544
www.Sohrabpoor.com
Example
var x = document.getElementById("myTime");
Try it Yourself »
Tip: You can also access <input type="time"> by searching through the elements collection
of a form.
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "time");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a time field
autofocus Sets or returns whether a time field should automatically get focus when the
page loads
545
www.Sohrabpoor.com
form Returns a reference to the form that contains the time field
list Returns a reference to the datalist that contains the time field
max Sets or returns the value of the max attribute of the time field
min Sets or returns the value of the min attribute of the time field
name Sets or returns the value of the name attribute of a time field
required Sets or returns whether the time field must be filled out before submitting a
form
step Sets or returns the value of the step attribute of the time field
value Sets or returns the value of the value attribute of a time field
546
www.Sohrabpoor.com
The Input URL object represents an HTML <input> element with type="url".
Example
var x = document.getElementById("myUrl");
Try it Yourself »
547
www.Sohrabpoor.com
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "url");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a URL field
autofocus Sets or returns whether a URL field should automatically get focus when the
page loads
form Returns a reference to the form that contains the URL field
list Returns a reference to the datalist that contains the URL field
maxLength Sets or returns the value of the maxlength attribute of a URL field
name Sets or returns the value of the name attribute of a URL field
548
www.Sohrabpoor.com
pattern Sets or returns the value of the pattern attribute of a URL field
placeholder Sets or returns the value of the placeholder attribute of a URL field
required Sets or returns whether the URL field must be filled out before submitting a
form
size Sets or returns the value of the size attribute of the URL field
value Sets or returns the value of the value attribute of a URL field
549
www.Sohrabpoor.com
Example
var x = document.getElementById("myWeek");
Try it Yourself »
Example
var x = document.createElement("INPUT");
x.setAttribute("type", "week");
Try it Yourself »
autocomplete Sets or returns the value of the autocomplete attribute of a week field
autofocus Sets or returns whether a week field should automatically get focus when the
page loads
550
www.Sohrabpoor.com
form Returns a reference to the form that contains the week field
list Returns a reference to the datalist that contains the week field
max Sets or returns the value of the max attribute of the week field
min Sets or returns the value of the min attribute of the week field
name Sets or returns the value of the name attribute of a week field
required Sets or returns whether the week field must be filled out before submitting a
form
step Sets or returns the value of the step attribute of the week field
value Sets or returns the value of the value attribute of a week field
551
www.Sohrabpoor.com
Example
var x = document.getElementById("myKbd");
Try it Yourself »
Example
var x = document.createElement("KBD");
552
www.Sohrabpoor.com
Try it Yourself »
Example
var x = document.getElementById("myKeygen");
Try it Yourself »
Example
var x = document.createElement("KEYGEN");
Try it Yourself »
553
www.Sohrabpoor.com
autofocus Sets or returns whether a keygen field automatically gets focus when the page
loads, or not
challenge Sets or returns the value of the challenge attribute of a keygen field
form Returns a reference to the form that contains the keygen field
keytype Sets or returns the value of the keytype attribute of a keygen field
name Sets or returns the value of the name attribute of a keygen field
554
www.Sohrabpoor.com
Example
var x = document.getElementById("myLabel");
Try it Yourself »
Example
var x = document.createElement("LABEL");
Try it Yourself »
555
www.Sohrabpoor.com
Example
var x = document.getElementById("myLegend");
Try it Yourself »
Example
var x = document.createElement("LEGEND");
Try it Yourself »
556
www.Sohrabpoor.com
Access a Li Object
You can access a <li> element by using getElementById():
Example
var x = document.getElementById("myLi");
Try it Yourself »
Create a Li Object
You can create a <li> element by using the document.createElement()
method:
Example
var x = document.createElement("LI");
Try it Yourself »
Li Object Properties
Property Description
value Sets or returns the value of the value attribute of a list item
557
www.Sohrabpoor.com
Example
var x = document.getElementById("myLink");
Try it Yourself »
Example
var x = document.createElement("LINK");
Try it Yourself »
558
www.Sohrabpoor.com
Property Description
crossOrigin Sets or returns the the CORS settings of the linked document
media Sets or returns the media type for the link element
rel Sets or returns the relationship between the current document and the linked
document
sizes Returns the value of the sizes attribute of the linked resource
559
www.Sohrabpoor.com
Example
var x = document.getElementById("myMap");
Try it Yourself »
Example
var x = document.createElement("MAP");
Try it Yourself »
560
www.Sohrabpoor.com
images Returns a collection of all <img> and <object> elements associated with the
image-map
Example
var x = document.getElementById("myMark");
Try it Yourself »
561
www.Sohrabpoor.com
Example
var x = document.createElement("MARK");
Try it Yourself »
Note: The <menu> element is currently NOT supported in any of the major
browsers.
var x = document.getElementById("myMenu");
var x = document.createElement("MENU");
562
www.Sohrabpoor.com
label Sets or returns the value of the label attribute of the menu
type Sets or returns the value of the type attribute of the menu
var x = document.getElementById("myMenuItem");
var x = document.createElement("MENUITEM");
563
www.Sohrabpoor.com
command Sets or returns the value of the command attribute of the menu item
default Sets or returns whether the menu item should be the default command
label Sets or returns the value of the label attribute of the menu item
radiogroup Sets or returns the value of the radiogroup attribute of the menu item
type Sets or returns the value of the type attribute of the menu item
564
www.Sohrabpoor.com
var x = document.getElementsByTagName("META")[0];
Try it Yourself »
Example
var x = document.createElement("META");
Try it Yourself »
content Sets or returns the value of the content attribute of a meta element
httpEquiv Sets or returns an HTTP header for the information in the content attribute
name Sets or returns a name for the information in the content attribute
565
www.Sohrabpoor.com
Example
var x = document.getElementById("myMeter");
Try it Yourself »
Example
var x = document.createElement("METER");
Try it Yourself »
566
www.Sohrabpoor.com
labels Returns a list of <label> elements that are labels for the gauge
567
www.Sohrabpoor.com
Note: The <nav> element is not supported in Internet Explorer 8 and earlier
versions.
Example
var x = document.getElementById("myNav");
Try it Yourself »
Example
var x = document.createElement("NAV");
Try it Yourself »
Example
var x = document.getElementById("myObject");
Try it Yourself »
568
www.Sohrabpoor.com
Example
var x = document.createElement("OBJECT");
Try it Yourself »
Object Properties
= Property added in HTML5.
Property Description
569
www.Sohrabpoor.com
data Sets or returns the URL of the resource to be used by the object
type Sets or returns the content type for data downloaded via the data attribute
useMap Sets or returns the name of a client-side image map to be used with the object
570
www.Sohrabpoor.com
Access an Ol Object
You can access an <ol> element by using getElementById():
Example
var x = document.getElementById("myOl");
Try it Yourself »
Create an Ol Object
You can create an <ol> element by using the document.createElement()
method:
Example
var x = document.createElement("OL");
Try it Yourself »
Ol Object Properties
Property Description
reversed Sets or returns whether the list order should be descending or not
571
www.Sohrabpoor.com
start Sets or returns the value of the start attribute of an ordered list
type Sets or returns the value of the type attribute of an ordered list
Example
var x = document.getElementById("myOptgroup");
Try it Yourself »
Example
var x = document.createElement("OPTGROUP");
Try it Yourself »
572
www.Sohrabpoor.com
Example
var x = document.getElementById("myOption");
Try it Yourself »
573
www.Sohrabpoor.com
Example
var x = document.createElement("OPTION");
Try it Yourself »
label Sets or returns the value of the label attribute of an option in a drop-down
list
574
www.Sohrabpoor.com
Example
var x = document.getElementById("myOutput");
Try it Yourself »
Example
var x = document.createElement("OUTPUT");
Try it Yourself »
575
www.Sohrabpoor.com
form Returns a reference to the form that contains the <output> element
labels Returns a list of <label> elements associated with the <output> element
name Sets or returns the value of the name attribute of an <output> element
type Returns which type of HTML element the Output object represents
Example
var x = document.getElementById("myP");
Try it Yourself »
576
www.Sohrabpoor.com
Example
var x = document.createElement("P");
Try it Yourself »
577
www.Sohrabpoor.com
Example
var x = document.getElementById("myParam");
Try it Yourself »
Example
var x = document.createElement("PARAM");
Try it Yourself »
578
www.Sohrabpoor.com
Example
var x = document.getElementById("myPre");
Try it Yourself »
Example
var x = document.createElement("PRE");
Try it Yourself »
579
www.Sohrabpoor.com
Example
var x = document.getElementById("myProgress");
Try it Yourself »
Example
var x = document.createElement("PROGRESS");
Try it Yourself »
max Sets or returns the value of the max attribute of a progress bar
580
www.Sohrabpoor.com
value Sets or returns the value of the value attribute of a progress bar
Example
var x = document.getElementById("myQuote");
Try it Yourself »
Example
var x = document.createElement("Q");
Try it Yourself »
581
www.Sohrabpoor.com
Access a S Object
You can access a <s> element by using getElementById():
Example
var x = document.getElementById("myS");
Try it Yourself »
Create a S Object
You can create a <s> element by using the document.createElement()
method:
Example
var x = document.createElement("S");
Try it Yourself »
582
www.Sohrabpoor.com
Example
var x = document.getElementById("mySamp");
Try it Yourself »
Example
var x = document.createElement("SAMP");
Try it Yourself »
583
www.Sohrabpoor.com
Example
var x = document.getElementById("myScript");
Try it Yourself »
Tip: You can also access a <script> element by using the scripts collection.
Example
var x = document.createElement("SCRIPT");
Try it Yourself »
Property Description
584
www.Sohrabpoor.com
defer Sets or returns whether a script should be executed when the page has finished
parsing
text Sets or returns the contents of all the text nodes that are children of a script
Example
var x = document.getElementById("mySection");
Try it Yourself »
585
www.Sohrabpoor.com
Example
var x = document.createElement("SECTION");
Try it Yourself »
Example
var x = document.getElementById("mySelect");
Try it Yourself »
Example
var x = document.createElement("SELECT");
Try it Yourself »
586
www.Sohrabpoor.com
form Returns a reference to the form that contains the drop-down list
multiple Sets or returns whether more than one option can be selected from the drop-
down list
name Sets or returns the value of the name attribute of a drop-down list
selectedIndex Sets or returns the index of the selected option in a drop-down list
587
www.Sohrabpoor.com
value Sets or returns the value of the selected option in a drop-down list
Example
var x = document.getElementById("mySmall");
Try it Yourself »
588
www.Sohrabpoor.com
Example
var x = document.createElement("SMALL");
Try it Yourself »
Example
var x = document.getElementById("mySource");
Try it Yourself »
Example
var x = document.createElement("SOURCE");
Try it Yourself »
589
www.Sohrabpoor.com
media Sets or returns the value of the media attribute in a <source> element
src Sets or returns the value of the src attribute in a <source> element
type Sets or returns the value of the type attribute in a <source> element
Example
var x = document.getElementById("mySpan");
Try it Yourself »
590
www.Sohrabpoor.com
Example
var x = document.createElement("SPAN");
Try it Yourself »
Example
var x = document.getElementById("myStrong");
Try it Yourself »
Example
var x = document.createElement("STRONG");
Try it Yourself »
591
www.Sohrabpoor.com
Example
var x = document.getElementsByTagName("STYLE");
Try it Yourself »
Example
var x = document.getElementById("myH1").style;
Try it Yourself »
Example
var x = document.createElement("STYLE");
Try it Yourself »
Example
document.getElementById("myH1").style.color = "red";
Try it Yourself »
592
www.Sohrabpoor.com
alignContent Sets or returns the alignment between the lines inside a flexible 3
container when the items do not use all available space
alignItems Sets or returns the alignment for items inside a flexible container 3
alignSelf Sets or returns the alignment for selected items inside a flexible 3
container
animation A shorthand property for all the animation properties below, except the 3
animationPlayState property
animationDire Sets or returns whether or not the animation should play in reverse on 3
ction alternate cycles
animationFillM Sets or returns what values are applied by the animation outside the time 3
ode it is executing
593
www.Sohrabpoor.com
594
www.Sohrabpoor.com
backfaceVisibili Sets or returns whether or not an element should be visible when not 3
ty facing the screen
borderBottom Sets or returns the shape of the border of the bottom-left corner 3
LeftRadius
borderBottom Sets or returns the shape of the border of the bottom-right corner 3
RightRadius
595
www.Sohrabpoor.com
borderCollapse Sets or returns whether the table border should be collapsed into a single 2
border, or not
borderColor Sets or returns the color of an element's border (can have up to four 1
values)
borderImageO Sets or returns the amount by which the border image area extends 3
utset beyond the border box
596
www.Sohrabpoor.com
borderRadius A shorthand property for setting or returning all the four border*Radius 3
properties
borderStyle Sets or returns the style of an element's border (can have up to four 1
values)
597
www.Sohrabpoor.com
borderTopLeft Sets or returns the shape of the border of the top-left corner 3
Radius
borderTopRigh Sets or returns the shape of the border of the top-right corner 3
tRadius
borderWidth Sets or returns the width of an element's border (can have up to four 1
values)
boxSizing Allows you to define certain elements to fit an area in a certain way 3
598
www.Sohrabpoor.com
clear Sets or returns the position of the element relative to floating objects 1
columnCount Sets or returns the number of columns an element should be divided into 3
columnSpan Sets or returns how many columns an element should span across 3
599
www.Sohrabpoor.com
content Used with the :before and :after pseudo-elements, to insert generated 2
content
cursor Sets or returns the type of cursor to display for the mouse pointer 2
emptyCells Sets or returns whether to show the border and background of empty 2
cells, or not
filter Sets or returns image filters (visual effects, like blur and saturation) 3
flex Sets or returns the length of the item, relative to the rest 3
600
www.Sohrabpoor.com
flexFlow A shorthand property for the flexDirection and the flexWrap properties 3
flexGrow Sets or returns how much the item will grow relative to the rest 3
flexShrink Sets or returns how the item will shrink relative to the rest 3
flexWrap Sets or returns whether the flexible items should wrap or not 3
fontStyle Sets or returns whether the style of the font is normal, italic or oblique 1
fontVariant Sets or returns whether the font should be displayed in small capital 1
letters
601
www.Sohrabpoor.com
hangingPunctu Specifies whether a punctuation character may be placed outside the line 3
ation box
icon Provides the author the ability to style an element with an iconic 3
equivalent
imageOrientati Specifies a rotation in the right or clockwise direction that a user agent 3
on applies to an image
justifyContent Sets or returns the alignment between the items inside a flexible 3
container when the items do not use all available space.
602
www.Sohrabpoor.com
margin Sets or returns the margins of an element (can have up to four values) 1
navDown Sets or returns where to navigate when using the arrow-down navigation 3
key
navLeft Sets or returns where to navigate when using the arrow-left navigation 3
key
603
www.Sohrabpoor.com
navRight Sets or returns where to navigate when using the arrow-right navigation 3
key
navUp Sets or returns where to navigate when using the arrow-up navigation 3
key
order Sets or returns the order of the flexible item, relative to the rest 3
orphans Sets or returns the minimum number of lines for an element that must be 2
left at the bottom of a page when a page break occurs inside an element
overflow Sets or returns what to do with content that renders outside the element 2
box
604
www.Sohrabpoor.com
padding Sets or returns the padding of an element (can have up to four values) 1
605
www.Sohrabpoor.com
position Sets or returns the type of positioning method used for an element 2
(static, relative, absolute or fixed)
quotes Sets or returns the type of quotation marks for embedded quotations 2
tableLayout Sets or returns the way to lay out table cells, rows, and columns 2
textAlignLast Sets or returns how the last line of a block or a line right before a forced 3
line break is aligned when text-align is "justify"
606
www.Sohrabpoor.com
textJustify Sets or returns the justification method used when text-align is "justify" 3
textOverflow Sets or returns what should happen when text overflows the containing 3
element
transitionProp Sets or returns the CSS property that the transition effect is for 3
erty
607
www.Sohrabpoor.com
whiteSpace Sets or returns how to handle tabs, line breaks and whitespace in a text 1
wordWrap Allows long, unbreakable words to be broken and wrap to the next line 3
widows Sets or returns the minimum number of lines for an element that must be 2
visible at the top of a page
608
www.Sohrabpoor.com
Example
var x = document.getElementById("mySub");
Try it Yourself »
Example
var x = document.createElement("SUB");
Try it Yourself »
609
www.Sohrabpoor.com
Example
var x = document.getElementById("mySummary");
Try it Yourself »
Example
var x = document.createElement("SUMMARY");
Try it Yourself »
Example
var x = document.getElementById("mySup");
Try it Yourself »
610
www.Sohrabpoor.com
Example
var x = document.createElement("SUP");
Try it Yourself »
Example
var x = document.getElementById("myTable");
Try it Yourself »
Example
var x = document.createElement("TABLE");
Try it Yourself »
611
www.Sohrabpoor.com
612
www.Sohrabpoor.com
613
www.Sohrabpoor.com
614
www.Sohrabpoor.com
Example
var x = document.getElementById("myTd");
Try it Yourself »
Example
var x = document.createElement("TD");
Try it Yourself »
615
www.Sohrabpoor.com
cellIndex Returns the position of a cell in the cells collection of a table row
616
www.Sohrabpoor.com
Example
var x = document.getElementById("myTh");
Try it Yourself »
617
www.Sohrabpoor.com
Example
var x = document.createElement("TH");
Try it Yourself »
cellIndex Returns the position of a cell in the cells collection of a table row
618
www.Sohrabpoor.com
height Not supported in HTML5. Sets or returns the height of a data cell
Use style.height instead
noWrap Not supported in HTML5. Sets or returns whether the content in a cell can be
wrapped
Use style.whiteSpace instead
vAlign Not supported in HTML5. Sets or returns the vertical alignment of the content
within a cell
Use style.verticalAlign instead
width Not supported in HTML5. Sets or returns the width of a data cell
Use style.width instead
619
www.Sohrabpoor.com
Example
var x = document.getElementById("myTr");
Try it Yourself »
Example
var x = document.createElement("TR");
Try it Yourself »
620
www.Sohrabpoor.com
sectionRowIndex Returns the position of a row in the rows collection of a tbody, thead, or tfoot
621
www.Sohrabpoor.com
Example
var x = document.getElementById("myTextarea");
Try it Yourself »
Example
var x = document.createElement("TEXTAREA");
Try it Yourself »
622
www.Sohrabpoor.com
Property Description
autofocus Sets or returns whether a text area should automatically get focus when the page
loads
cols Sets or returns the value of the cols attribute of a text area
form Returns a reference to the form that contains the text area
maxLength Sets or returns the value of the maxlength attribute of a text area
name Sets or returns the value of the name attribute of a text area
placeholder Sets or returns the value of the placeholder attribute of a text area
required Sets or returns whether the text area must be filled out before submitting a form
rows Sets or returns the value of the rows attribute of a text area
623
www.Sohrabpoor.com
type Returns the type of the form element the text area is
wrap Sets or returns the value of the wrap attribute of a text area
Example
var x = document.getElementById("myTime");
Try it Yourself »
624
www.Sohrabpoor.com
Example
var x = document.createElement("TIME");
Try it Yourself »
dateTime Sets or returns the value of the datetime attribute in a <time> element
Example
var x = document.getElementsByTagName("TITLE")[0];
Try it Yourself »
625
www.Sohrabpoor.com
Example
var x = document.createElement("TITLE");
Try it Yourself »
var x = document.getElementById("myTrack");
626
www.Sohrabpoor.com
var x = document.createElement("TRACK");
kind Sets or returns the value of the kind attribute of the track
label Sets or returns the value of the label attribute of the track
src Sets or returns the value of the src attribute of the track
srclang Sets or returns the value of the srclang attribute of the track
track Returns a TextTrack object representing the track element's text track data
627
www.Sohrabpoor.com
Example
var x = document.getElementById("myU");
Try it Yourself »
Example
var x = document.createElement("U");
Try it Yourself »
Access a Ul Object
You can access a <ul> element by using getElementById():
628
www.Sohrabpoor.com
Example
var x = document.getElementById("myUL");
Try it Yourself »
Create a Ul Object
You can create a <ul> element by using the document.createElement()
method:
Example
var x = document.createElement("UL");
Try it Yourself »
Ul Object Properties
Property Description
629
www.Sohrabpoor.com
Example
var x = document.getElementById("myVar");
Try it Yourself »
Example
var x = document.createElement("VAR");
Try it Yourself »
Note: The <video> element is not supported in Internet Explorer 8 and earlier versions.
630
www.Sohrabpoor.com
Example
var x = document.getElementById("myVideo");
Try it Yourself »
Example
var x = document.createElement("VIDEO");
Try it Yourself »
autoplay Sets or returns whether a video should start playing as soon as it is ready
631
www.Sohrabpoor.com
controls Sets or returns whether a video should have controls displayed (play/pause
etc)
currentTime Sets or returns the current playback position in a video (in seconds)
defaultPlaybackRate Sets or returns whether the default playback speed of the video
error Returns a MediaError object representing the error state of the video
loop Sets or returns whether the video should start playing over again, every
time it is finished
mediaGroup Sets or returns the name of the media group the video(s) is a part of
muted Sets or returns whether the sound of a video should be turned off
632
www.Sohrabpoor.com
played Returns a TimeRanges object representing the played parts of the video
633
www.Sohrabpoor.com
canPlayType() Checks whether the browser can play the specified video type
634