JavaScript MANUAL
JavaScript MANUAL
RWARE
COLLEGE
OF ACCOUNTS
JAVASCRIPT
TRAINING MANUAL
Rware College of Accounts
Web Design: JavaScript Training Manual
Contents
1. INTRODUCTION TO JAVASCRIPT .....................................................
1.1. JavaScript Getting Started ...........................................................
1.2. JavaScript Syntax .........................................................................
1.3. JavaScript Variables ....................................................................
1.4. JavaScript Generating Output .....................................................
2. JavaScript Data Types .....................................................................
3. JavaScript Operators .......................................................................
4. JavaScript Events.............................................................................
5. Mouse Events .................................................................................
6. Keyboard Events .............................................................................
7. Form Events ....................................................................................
8. Document/Window Events .............................................................
9. JavaScript Strings ............................................................................
10. JavaScript Numbers.....................................................................
11. JavaScript If…Else Statements .....................................................
12. JavaScript Switch...Case Statements ...........................................
13. JavaScript Arrays .........................................................................
14. JavaScript Loops ..........................................................................
15. JavaScript Functions ....................................................................
16. JavaScript Objects .......................................................................
17. Creating Objects..........................................................................
18. JavaScript DOM Nodes ................................................................
19. JavaScript DOM Selectors ...........................................................
20. JavaScript DOM Styling ...............................................................
21. Naming Conventions of CSS Properties in JavaScript ..................
22. JavaScript DOM Get Set Attributes .............................................
23. JavaScript DOM Manipulation ....................................................
24. JavaScript DOM Navigation .........................................................
25. JavaScript Window ......................................................................
26. JavaScript Window Screen ..........................................................
27. JavaScript Window Location .......................................................
28. JavaScript Window History .........................................................
29. JavaScript Window Navigator .....................................................
30. JavaScript Dialog Boxes ...............................................................
i
Rware College of Accounts
Web Design: JavaScript Training Manual
31. JavaScript Timers ........................................................................
32. JavaScript Form Validation ..........................................................
33. JavaScript Cookies .......................................................................
ii
Rware College of Accounts
Web Design: JavaScript Training Manual
1. INTRODUCTION TO JAVASCRIPT
1
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Embedding JavaScript</title>
</head>
<body>
<script>
var greet = "Hello World!";
document.write(greet); // Prints: Hello
World!
</script>
</body>
</html>
The JavaScript code in the above example will simply prints a
text message on the web page. You will learn what each of
these JavaScript statements means in upcoming chapters.
<script src="js/hello.js"></script>
2
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Including External JavaScript
File</title>
</head>
<body>
<button type="button" id="myBtn">Click
Me</button>
<script src="js/hello.js"></script>
</body>
</html>
Note: Usually when an external JavaScript file is downloaded
for first time, it is stored in the browser's cache (just like
images and style sheets), so it won't need to be downloaded
multiple times from the web server that makes the web pages
load more quickly.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inlining JavaScript</title>
</head>
<body>
<button onclick="alert('Hello
World!')">Click Me</button>
</body>
3
Rware College of Accounts
Web Design: JavaScript Training Manual
</html>
The above example will show you an alert message on click of
the button element.
4
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
You will learn what each of these statements means in
upcoming chapters.
Example
Try this code »
JavaScript Comments
A comment is simply a line of text that is completely ignored
by the JavaScript interpreter. Comments are usually added
with the purpose of providing extra information pertaining to
source code. It will not only help you understand your code
when you look after a period of time but also others who are
working with you on the same project.
Example
Try this code »
5
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
You can create a variable with the var keyword, whereas the
assignment operator (=) is used to assign value to a variable,
like this: var varName = value;
Example
Try this code »
Example
Try this code »
// Declaring Variable
var userName;
// Assigning value
userName = "Clark Kent";
Note: In JavaScript, if a variable has been declared, but has
not been assigned a value explicitly, is automatically assigned
the value undefined.
6
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
The const keyword works exactly the same as let, except that
variables declared using const keyword cannot be reassigned
later in the code. Here's an example:
Example
Try this code »
// Declaring variables
let name = "Harry Potter";
let age = 11;
let isStudent = true;
// Declaring constant
const PI = 3.14;
console.log(PI); // 3.14
// Trying to reassign
PI = 10; // error
Unlike var, which declare function-scoped variables,
both let and const keywords declare variables, scoped at
block-level ({}). Block scoping means that a new scope is
created between a pair of curly brackets {}. We'll discuss this
in detail later, in JavaScript ES6 features chapter.
7
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
8
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<button type="button"
onclick="document.write('Hello World!')">Click
Me</button>
Example
Try this code »
<p id="greet"></p>
<p id="result"></p>
<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML =
"Hello World!";
9
Rware College of Accounts
Web Design: JavaScript Training Manual
var x = 10;
var y = 20;
var sum = x + y;
document.getElementById("result").innerHTML =
sum;
</script>
You will learn about manipulating HTML element in detail
in JavaScript DOM manipulation chapter.
Example
Try this code »
Example
Try this code »
10
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
11
Rware College of Accounts
Web Design: JavaScript Training Manual
var a = 2, b = 5, c = 10;
Example
Try this code »
var a;
var b = "Hello World!"
Example
Try this code »
var a = null;
alert(a); // Output: null
b = null;
alert(b) // Output: null
Example
Try this code »
12
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var car = {
modal: "BMW X3",
color: "white",
doors: 5
}
Example
Try this code »
Example
Try this code »
13
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
function createGreeting(name){
return "Hello, " + name;
}
function displayGreeting(greetingFunction,
userName){
return greetingFunction(userName);
}
Example
Try this code »
// Numbers
typeof 15; // Returns: "number"
typeof 42.7; // Returns: "number"
typeof 2.5e-4; // Returns: "number"
typeof Infinity; // Returns: "number"
typeof NaN; // Returns: "number". Despite
being "Not-A-Number"
// Strings
typeof ''; // Returns: "string"
typeof 'hello'; // Returns: "string"
typeof '12'; // Returns: "string". Number
within quotes is typeof string
// Booleans
typeof true; // Returns: "boolean"
typeof false; // Returns: "boolean"
// Undefined
typeof undefined; // Returns: "undefined"
14
Rware College of Accounts
Web Design: JavaScript Training Manual
// Null
typeof Null; // Returns: "object"
// Objects
typeof {name: "John", age: 18}; // Returns:
"object"
// Arrays
typeof [1, 2, 4]; // Returns: "object"
// Functions
typeof function(){}; // Returns: "function"
As you can clearly see in the above example when we test
the null value using the typeof operator (line no-22), it
returned "object" instead of "null".
3. JavaScript Operators
+ Addition x + y Sum of x
- Subtraction x - y Differenc
* Multiplication x * y Product o
/ Division x / y Quotient
15
Rware College of Accounts
Web Design: JavaScript Training Manual
% Modulus x % y Remainde
Example
Try this code »
var x = 10;
var y = 4;
alert(x + y); // 0utputs: 14
alert(x - y); // 0utputs: 6
alert(x * y); // 0utputs: 40
alert(x / y); // 0utputs: 2.5
alert(x % y); // 0utputs: 2
= Assign x = y
Example
Try this code »
x = 10;
alert(x); // Outputs: 10
x = 20;
x += 30;
alert(x); // Outputs: 50
x = 50;
x -= 20;
alert(x); // Outputs: 30
16
Rware College of Accounts
Web Design: JavaScript Training Manual
x = 5;
x *= 25;
alert(x); // Outputs: 125
x = 50;
x /= 10;
alert(x); // Outputs: 5
x = 100;
x %= 15;
alert(x); // Outputs: 10
Example
Try this code »
str1 += str2;
alert(str1); // Outputs: Hello World!
17
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
x = 10;
alert(++x); // Outputs: 11
alert(x); // Outputs: 11
x = 10;
alert(x++); // Outputs: 10
alert(x); // Outputs: 11
x = 10;
alert(--x); // Outputs: 9
alert(x); // Outputs: 9
x = 10;
alert(x--); // Outputs: 10
alert(x); // Outputs: 9
|| Or x || y True if either x or y
Example
Try this code »
18
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var x = 25;
var y = 35;
var z = "25";
4. JavaScript Events
19
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
5. Mouse Events
20
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
21
Rware College of Accounts
Web Design: JavaScript Training Manual
6. Keyboard Events
You can handle the keydown event with the onkeydown event
handler. The following example will show you an alert
message when the keydown event occurs.
Example
Try this code »
You can handle the keyup event with the onkeyup event
handler. The following example will show you an alert
message when the keyup event occurs.
Example
Try this code »
You can handle the keypress event with the onkeypress event
handler. The following example will show you an alert
message when the keypress event occurs.
22
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
7. Form Events
You can handle the focus event with the onfocus event
handler. The following example will highlight the background
of text input in yellow color when it receives the focus.
Example
Try this code »
<script>
function highlightInput(elm){
elm.style.background = "yellow";
}
</script>
<input type="text"
onfocus="highlightInput(this)">
<button type="button">Button</button>
Note: The value of this keyword inside an event handler
refers to the element which has the handler on it (i.e. where
the event is currently being delivered).
You can handle the blur event with the onblur event handler.
The following example will show you an alert message when
the text input element loses focus.
Example
Try this code »
23
Rware College of Accounts
Web Design: JavaScript Training Manual
You can handle the change event with the onchange event
handler. The following example will show you an alert
message when you change the option in the select box.
Example
Try this code »
You can handle the submit event with the onsubmit event
handler. The following example will show you an alert
message while submitting the form to the server.
Example
Try this code »
8. Document/Window Events
You can handle the load event with the onload event handler.
The following example will show you an alert message as
soon as the page finishes loading.
Example
Try this code »
24
Rware College of Accounts
Web Design: JavaScript Training Manual
You can handle the unload event with the onunload event
handler. The following example will show you an alert
message when you try to leave the page.
Example
Try this code »
You can handle the resize event with the onresize event
handler. The following example will show you an alert
message when you resize the browser window to a new width
and height.
Example
Try this code »
<p id="result"></p>
<script>
function displayWindowSize() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w +
", height=" + h;
document.getElementById("result").innerHTML =
txt;
}
window.onresize = displayWindowSize;
</script>
9. JavaScript Strings
25
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
26
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
27
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
// Searching forwards
var pos1 = str.indexOf("facts", 20);
alert(pos1); // 0utputs: 46
// Searching backwards
var pos2 = str.lastIndexOf("facts", 20);
alert(pos2); // 0utputs: 7
Note: Characters in a string are indexed from left to right. The
index of the first character is 0, and the index of the last
character of a string called myStr is myStr.length - 1.
Example
Try this code »
28
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
29
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
30
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
31
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
32
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
33
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
var x = 10;
var y = 20;
var z = "30";
34
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var x = 10;
var y = 20;
var z = "30";
Example
Try this code »
var x = 10;
var y = "foo";
var z = NaN;
35
Rware College of Accounts
Web Design: JavaScript Training Manual
Representing Infinity
Infinity represents a number too big for JavaScript to handle.
JavaScript has special keyword Infinity and -Infinity to
represent positive and negative infinity respectively. For
example, dividing by 0 returns Infinity, as demonstrated
below:
Example
Try this code »
var x = 5 / 0;
console.log(x); // Infinity
var y = -5 / 0;
console.log(y); // -Infinity
Note: Infinity is a special value that represents the
mathematical Infinity ∞, which is greater than any number.
The typeof operator return number for an Infinity value.
Example
Try this code »
To avoid this problem you can use the solution something like
this:
Example
Try this code »
Example
Try this code »
var x = 999999999999999;
console.log(x); // 999999999999999
36
Rware College of Accounts
Web Design: JavaScript Training Manual
var y = 9999999999999999;
console.log(y); // 10000000000000000
Example
Try this code »
console.log(parseInt("3.14")); // 3
console.log(parseInt("50px")); // 50
console.log(parseInt("12pt")); // 12
console.log(parseInt("0xFF", 16)); // 255
console.log(parseInt("20 years")); // 20
console.log(parseInt("Year 2048")); // NaN
console.log(parseInt("10 12 2018")); // 10
Note: The parseInt() method truncates numbers to integer
values, but it should not be used as a substitute
for Math.floor() method.
Similarly, you can use the parseFloat() method to parse
floating-point number from a string.
The parseFloat() method works the same way as
the parseInt() method, except that it retrieves both integers
and numbers with decimals.
Example
Try this code »
console.log(parseFloat("3.14")); // 3.14
console.log(parseFloat("50px")); // 50
console.log(parseFloat("1.6em")); // 1.6
console.log(parseFloat("124.5 lbs")); // 124.5
console.log(parseFloat("weight 124.5 lbs"));
// NaN
console.log(parseFloat("6.5 acres")); // 6.5
37
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var x = 10;
var y = x.toString();
console.log(y); // '10'
console.log(typeof y); // string
console.log(typeof x); // number
console.log((12).toString()); // '12'
console.log((15.6).toString()); // '15.6'
console.log((6).toString(2)); // '110'
console.log((255).toString(16)); // 'ff'
Example
Try this code »
var x = 67.1234;
console.log(x.toExponential()); // 6.71234e+1
console.log(x.toExponential(6)); //
6.712340e+1
console.log(x.toExponential(4)); // 6.7123e+1
console.log(x.toExponential(2)); // 6.71e+1
Note: Exponential notation is useful for representing numbers
that are either very large or very small in magnitude. For
example, 62500000000 can be written as 625e+8 or 6.25e+10.
Example
Try this code »
var x = 72.635;
38
Rware College of Accounts
Web Design: JavaScript Training Manual
var y = 6.25e+5;
console.log(y.toFixed(2)); // '625000.00'
var z = 1.58e-4;
console.log(z.toFixed(2)); // '0.00' (since
1.58e-4 is equal to 0.000158)
Example
Try this code »
var x = 6.235;
console.log(x.toPrecision()); // '6.235'
console.log(x.toPrecision(3)); // '6.24' (note
rounding)
console.log(x.toPrecision(2)); // '6.2'
console.log(x.toPrecision(1)); // '6'
var y = 47.63;
console.log(y.toPrecision(2)); // '48' (note
rounding, no fractional part)
var z = 1234.5;
console.log(z.toPrecision(2)); // '1.2e+3'
Example
Try this code »
var a = Number.MAX_VALUE;
console.log(a); // 1.7976931348623157e+308
39
Rware College of Accounts
Web Design: JavaScript Training Manual
var b = Number.MIN_VALUE;
console.log(b); // 5e-324
var x = Number.MAX_VALUE * 2;
console.log(x); // Infinity
var y = -1 * Number.MAX_VALUE * 2;
console.log(y); // -Infinity
Also, check out the JavaScript math operations chapter to
learn about rounding numbers, generating a random number,
finding maximum or minimun value from a set of numbers,
etc.
The if statement
The if...else statement
The if...else if....else statement
The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the
specified condition evaluates to true. This is the simplest
JavaScript's conditional statements and can be written like:
if(condition) {
// Code to be executed
}
Example
Try this code »
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}
40
Rware College of Accounts
Web Design: JavaScript Training Manual
if(condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
Example
Try this code »
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}
if(condition1) {
// Code to be executed if condition1 is true
} else if(condition2) {
// Code to be executed if the condition1 is
false and condition2 is true
} else {
// Code to be executed if both condition1 and
condition2 are false
}
Example
Try this code »
41
Rware College of Accounts
Web Design: JavaScript Training Manual
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else if(dayOfWeek == 0) {
alert("Have a nice Sunday!");
} else {
alert("Have a nice day!");
}
Example
Try this code »
var userType;
var age = 21;
if(age < 18) {
userType = 'Child';
} else {
userType = 'Adult';
}
alert(userType); // Displays Adult
Using the ternary operator the same code could be written in
a more compact way:
Example
Try this code »
42
Rware College of Accounts
Web Design: JavaScript Training Manual
switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different
from all values
}
Example
Try this code »
switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday.");
break;
case 6:
alert("Today is Saturday.");
break;
default:
alert("No information available
for that day.");
break;
}
The getDay() method returns the weekday as a number from
0 and 6, where 0 represents Sunday. See the JavaScript date
and time chapter to learn more about date methods.
43
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
switch(d.getDay()) {
default:
alert("Looking forward to the
weekend.");
break;
case 6:
alert("Today is Saturday.");
break;
case 0:
alert("Today is Sunday.");
}
Example
Try this code »
44
Rware College of Accounts
Web Design: JavaScript Training Manual
switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}
Example
Try this code »
Creating an Array
The simplest way to create an array in JavaScript is enclosing
a comma-separated list of values in square brackets ([]), as
shown in the following syntax:
45
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Array indexes are zero-based. This means that the first item of
an array is stored at index 0, not 1, the second item is stored
at index 1, and so on. Array indexes start at 0 and go up to
the number of elements minus 1. So, array of five elements
would have indexes from 0 to 4.
Example
Try this code »
Example
Try this code »
46
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
Example
Try this code »
47
Rware College of Accounts
Web Design: JavaScript Training Manual
document.write(colors); // Prints:
Red,Green,Blue,Yellow
document.write(colors.length); // Prints: 4
Similarly, to add a new element at the beginning of an array
use the unshift() method, like this:
Example
Try this code »
document.write(colors); // Prints:
Yellow,Red,Green,Blue
document.write(colors.length); // Prints: 4
You can also add multiple elements at once using
the push() and unshift() methods, like this:
Example
Try this code »
document.write(colors); // Prints:
Yellow,Grey,Red,Green,Blue,Pink,Voilet
document.write(colors.length); // Prints: 7
Example
Try this code »
Example
Try this code »
48
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
49
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
document.write(colors.join()); // Prints:
Red,Green,Blue
document.write(colors.join("")); // Prints:
RedGreenBlue
document.write(colors.join("-")); // Prints:
Red-Green-Blue
document.write(colors.join(", ")); // Prints:
Red, Green, Blue
You can also convert an array to a comma-separated string
using the toString(). This method does not accept the
separator parameter like join(). Here's an example:
Example
Try this code »
Example
Try this code »
50
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
document.write(fruits.slice(2)); // Prints:
Mango,Orange,Papaya
document.write(fruits.slice(-2)); // Prints:
Orange,Papaya
document.write(fruits.slice(2, -1)); // Prints:
Mango,Orange
Example
Try this code »
Example
Try this code »
Example
Try this code »
51
Rware College of Accounts
Web Design: JavaScript Training Manual
document.write(fruits.indexOf("Apple")); //
Prints: 0
document.write(fruits.indexOf("Banana")); //
Prints: 1
document.write(fruits.indexOf("Pineapple")); //
Prints: -1
Both methods also accept an optional integer parameter from
index which specifies the index within the array at which to
start the search. Here's an example:
Example
Try this code »
Example
Try this code »
document.write(arr.includes(1)); // Prints:
true
document.write(arr.includes(6)); // Prints:
false
document.write(arr.includes(1, 2)); // Prints:
true
document.write(arr.includes(3, 4)); // Prints:
false
If you want to search an array based on certain condition then
you can use the JavaScript find() method which is newly
introduced in ES6. This method returns the value of the first
element in the array that satisfies the provided testing
function. Otherwise it return undefined.
Example
Try this code »
52
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
Example
Try this code »
Example
Try this code »
alert(fruits); // Outputs:
Apple,Banana,Mango,Orange,Papaya
alert(sorted); // Outputs:
Apple,Banana,Mango,Orange,Papaya
Reversing an Array
You can use the reverse() method to reverse the order of the
elements of an array.
53
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
alert(counts); // Outputs:
five,four,three,two,one
alert(reversed); // Output:
five,four,three,two,one
Note: The sort() and reverse() method modifies the
original array and return a reference to the same array, as you
can see in the above examples.
Example
Try this code »
To fix this sorting problem with numeric array, you can pass a
compare function, like this:
Example
Try this code »
54
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7
The apply() method provides a convenient way to pass array
values as arguments to a function that accepts multiple
arguments in an array-like manner, but not an array
(e.g. Math.max() and Math.min() methods here). So, the
resulting statement Math.max.apply(null, numbers) in the
example above is equivalent to the Math.max(3, -7, 10, 8,
15, 2).
Example
Try this code »
var persons = [
{ name: "Harry", age: 14 },
55
Rware College of Accounts
Web Design: JavaScript Training Manual
// Sort by age
persons.sort(function (a, b) {
return a.age - b.age;
});
console.log(persons);
// Sort by name
persons.sort(function(a, b) {
var x = a.name.toLowerCase(); // ignore
upper and lowercase
var y = b.name.toLowerCase(); // ignore
upper and lowercase
if(x < y) {
return -1;
}
if(x > y) {
return 1;
}
// names must be equal
return 0;
});
console.log(persons);
Loops are used to execute the same block of code again and
again, as long as a certain condition is met. The basic idea
behind a loop is to automate the repetitive tasks within a
program to save the time and effort. JavaScript now supports
five different types of loops:
56
Rware College of Accounts
Web Design: JavaScript Training Manual
fails, the loop is stopped. The generic syntax of the while loop
is:
while(condition) {
// Code to be executed
}
Example
Try this code »
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i +
"</p>");
i++;
}
Note: Make sure that the condition specified in your loop
eventually goes false. Otherwise, the loop will never stop
iterating which is known as infinite loop. A common mistake is
to forget to increment the counter variable (variable i in our
case).
do {
// Code to be executed
}
while(condition);
Example
Try this code »
var i = 1;
do {
document.write("<p>The number is " + i +
"</p>");
i++;
}
while(i <= 5);
57
Rware College of Accounts
Web Design: JavaScript Training Manual
With a do-while loop, on the other hand, the loop will always
be executed once even if the conditional expression evaluates
to false, because unlike the while loop, the condition is
evaluated at the end of the loop iteration rather than the
beginning.
The following example defines a loop that starts with i=1. The
loop will continued until the value of variable i is less than or
equal to 5. The variable i will increase by 1 each time the loop
runs:
Example
Try this code »
Example
Try this code »
58
Rware College of Accounts
Web Design: JavaScript Training Manual
for(variable in object) {
// Code to be executed
}
The following example will show you how to loop through all
properties of a JavaScript object.
Example
Try this code »
Example
Try this code »
59
Rware College of Accounts
Web Design: JavaScript Training Manual
Also, the code inside the loop is executed for each element of
the iterable object.
Example
Try this code »
60
Rware College of Accounts
Web Design: JavaScript Training Manual
The following section will show you how to define and call
functions in your scripts.
function functionName() {
// Code to be executed
}
Example
Try this code »
// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}
// Calling function
sayHello(); // 0utputs: Hello, welcome to this
website!
Once a function is defined it can be called (invoked) from
anywhere in the document, by typing its name followed by a
set of parentheses, like sayHello() in the example above.
Parameters are set on the first line of the function inside the
set of parentheses, like this:
61
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
alert(total);
}
// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12
You can define as many parameters as you like. However for
each parameter you specify, a corresponding argument needs
to be passed to the function when it is called, otherwise its
value becomes undefined. Let's consider the following
example:
Example
Try this code »
// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}
// Calling function
showFullname("Clark", "Kent"); // 0utputs:
Clark Kent
showFullname("John"); // 0utputs: John
undefined
Example
Try this code »
Example
Try this code »
function sayHello(name) {
var name = name || 'Guest';
alert('Hello, ' + name);
62
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
Example
Try this code »
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}
Example
Try this code »
63
Rware College of Accounts
Web Design: JavaScript Training Manual
// Function Declaration
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Function Expression
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};
Once function expression has been stored in a variable, the
variable can be used as a function:
Example
Try this code »
Example
Try this code »
64
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
// Defining function
function greetWorld() {
var greet = "Hello World!";
alert(greet);
}
Example
Try this code »
// Defining function
function greetWorld() {
alert(greet);
}
65
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
The above example creates an object called person that has
three properties name, age, and gender and one
method displayName(). The displayName() method displays
the value of this.name, which resolves to person.name. This is
the easiest and preferred way to create a new object in
JavaScript, which is known as object literals syntax.
Example
Try this code »
var person = {
"first name": "Peter",
"current age": 28,
gender: "Male"
66
Rware College of Accounts
Web Design: JavaScript Training Manual
};
Note: Since ECMAScript 5, reserved words can be used as
object's property names without quoting. However, you
should avoid doing this for better compatibility.
Example
Try this code »
var book = {
"name": "Harry Potter and the Goblet of
Fire",
"author": "J. K. Rowling",
"year": 2000
};
// Dot notation
document.write(book.author); // Prints: J. K.
Rowling
// Bracket notation
document.write(book["year"]); // Prints: 2000
The dot notation is easier to read and write, but it cannot
always be used. If the name of the property is not valid (i.e. if
it contains spaces or special characters), you cannot use the
dot notation; you'll have to use bracket notation, as shown in
the following example:
Example
Try this code »
var book = {
name: "Harry Potter and the Goblet of
Fire",
author: "J. K. Rowling",
"publication date": "8 July 2000"
};
// Bracket notation
document.write(book["publication date"]); //
Prints: 8 July 2000
The square bracket notation offers much more flexibility than
dot notation. It also allows you to specify property names as
variables instead of just string literals, as shown in the
example below:
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
67
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
person["email"] = "[email protected]";
document.write(person.email); // Prints:
[email protected]
68
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
// Deleting property
delete person.age;
alert(person.age); // Outputs: undefined
Note: The delete operator only removes an object property
or array element. It has no effect on variables or declared
functions. However, you should avoid delete operator for
deleting an array element, as it doesn't change the array's
length, it just leaves a hole in the array.
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
Example
Try this code »
69
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
70
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>
The above HTML document can be represented by the
following DOM tree:
71
Rware College of Accounts
Web Design: JavaScript Training Manual
The <head> and <body> elements are also siblings since they
are at the same level. Further, the text content inside an
element is a child node of the parent element. So, for
example, "Mobile OS" is considered as a child node of
the <h1> that contains it, and so on.
HTML attributes such as id, class, title, style, etc. are also
considered as nodes in DOM hierarchy but they don't
72
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Topmost Elements</title>
</head>
<body>
<script>
73
Rware College of Accounts
Web Design: JavaScript Training Manual
alert(document.documentElement.getAttribute("la
ng")); // Outputs: en
alert(document.head.firstElementChild.nodeName)
; // Outputs: meta
</script>
</body>
</html>
But, be careful. If document.body is used before the <body> tag
(e.g. inside the <head>), it will return null instead of the body
element. Because the point at which the script is executed,
the <body> tag was not parsed by the browser,
so document.body is truly null at that point.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Document.body Demo</title>
<script>
alert("From HEAD: " + document.body); //
Outputs: null (since <body> is not parsed yet)
</script>
</head>
<body>
<script>
alert("From BODY: " + document.body); //
Outputs: HTMLBodyElement
</script>
</body>
</html>
Selecting Elements by ID
You can select an element based on its unique ID with
the getElementById() method. This is the easiest way to find
an HTML element in the DOM tree.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
74
Rware College of Accounts
Web Design: JavaScript Training Manual
<meta charset="utf-8">
<title>JS Select Element by ID</title>
</head>
<body>
<p id="mark">This is a paragraph of
text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
var match =
document.getElementById("mark");
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Class
Name</title>
</head>
<body>
<p class="test">This is a paragraph of
text.</p>
<div class="block test">This is another
paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting elements with class test
var matches =
document.getElementsByClassName("test");
75
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Tag
Name</title>
</head>
<body>
<p>This is a paragraph of text.</p>
<div class="test">This is another paragraph
of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting all paragraph elements
var matches =
document.getElementsByTagName("p");
76
Rware College of Accounts
Web Design: JavaScript Training Manual
This method returns a list of all the elements that matches the
specified selectors. You can examine it just like any array, as
shown in the following example:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS
Selectors</title>
</head>
<body>
<ul>
<li>Bread</li>
<li class="tick">Coffee</li>
<li>Pineapple Cake</li>
</ul>
<script>
// Selecting all li elements
var matches = document.querySelectorAll("ul
li");
77
Rware College of Accounts
Web Design: JavaScript Training Manual
JavaScript. You can set almost all the styles for the elements
like, fonts, colors, margins, borders, background images, text
alignment, width and height, position, and so on.
The following example will set the color and font properties of
an element with id="intro".
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Set Inline Styles Demo</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem =
document.getElementById("intro");
78
Rware College of Accounts
Web Design: JavaScript Training Manual
The following example will get the style information from the
element having id="intro".
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Get Element's Style Demo</title>
</head>
<body>
<p id="intro" style="color:red; font-
size:20px;">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem =
document.getElementById("intro");
To get the values of all CSS properties that are actually used
to render an element you can use
the window.getComputedStyle() method, as shown in the
following example:
Example
Try this code »
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Computed Style Demo</title>
<style type="text/css">
#intro {
font-weight: bold;
font-style: italic;
}
</style>
79
Rware College of Accounts
Web Design: JavaScript Training Manual
</head>
<body>
<p id="intro" style="color:red; font-
size:20px;">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem =
document.getElementById("intro");
alert(styles.getPropertyValue("color"));
// Outputs: rgb(255, 0, 0)
alert(styles.getPropertyValue("font-
size")); // Outputs: 20px
alert(styles.getPropertyValue("font-
weight")); // Outputs: 700
alert(styles.getPropertyValue("font-
style")); // Outputs: italic
</script>
</body>
</html>
Tip: The value 700 for the CSS property font-weight is same
as the keyword bold. The color keyword red is same
as rgb(255,0,0), which is the rgb notation of a color.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Add or Replace CSS Classes
Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something
very important!</div>
<script>
// Selecting element
var elem = document.getElementById("info");
80
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS classList Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something
very important!</div>
<script>
// Selecting element
var elem = document.getElementById("info");
81
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<a href="https://www.google.com/"
target="_blank" id="myLink">Google</a>
<script>
// Selecting the element by ID attribute
var link =
document.getElementById("myLink");
Example
Try this code »
<script>
// Selecting the element
var btn = document.getElementById("myBtn");
82
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
// Selecting the element
var link =
document.getElementById("myLink");
Example
Try this code »
<a href="https://www.google.com/"
id="myLink">Google</a>
<script>
// Selecting the element
var link =
document.getElementById("myLink");
83
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
// Creating a new div element
var newDiv = document.createElement("div");
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
// Creating a new div element
var newDiv = document.createElement("div");
84
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
// Getting inner HTML conents
var contents =
document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents
Example
Try this code »
<script>
// Selecting target element
var mainDiv = document.getElementById("main");
85
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
var parentElem =
document.getElementById("main");
var childElem =
document.getElementById("hint");
parentElem.removeChild(childElem);
</script>
It is also possible to remove the child element without exactly
knowing the parent element. Simply find the child element
and use the parentNode property to find its parent element.
This property returns the parent of the specified node in the
DOM tree. Here's an example:
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
86
Rware College of Accounts
Web Design: JavaScript Training Manual
<script>
var childElem =
document.getElementById("hint");
childElem.parentNode.removeChild(childElem);
</script>
Example
Try this code »
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
var parentElem =
document.getElementById("main");
var oldPara = document.getElementById("hint");
87
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var main = document.getElementById("main");
console.log(main.firstChild.nodeName); //
Prints: #text
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var main = document.getElementById("main");
alert(main.firstElementChild.nodeName); //
Outputs: H1
main.firstElementChild.style.color = "red";
88
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var main = document.getElementById("main");
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var main = document.getElementById("main");
89
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var hint = document.getElementById("hint");
alert(hint.parentNode.nodeName); // Outputs:
DIV
alert(document.documentElement.parentNode.nodeN
ame); // Outputs: #document
alert(document.parentNode); // Outputs: null
</script>
Tip: The topmost DOM tree nodes can be accessed directly
as document properties. For example, the <html> element
can be accessed with document.documentElement property,
whereas the <head> element can be accessed
with document.head property, and the <body> element can
be accessed with document.body property.
However, if you want to get only element nodes you can use
the parentElement, like this:
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var hint = document.getElementById("hint");
alert(hint.parentNode.nodeName); // Outputs:
DIV
hint.parentNode.style.backgroundColor =
"yellow";
</script>
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p><hr>
</div>
<script>
90
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some
text.</span></p>
</div>
<script>
var hint = document.getElementById("hint");
alert(hint.previousElementSibling.nodeName); //
Outputs: H1
alert(hint.previousElementSibling.textContent);
// Outputs: My Heading
Every node has a nodeType property that you can use to find
out what type of node you are dealing with. The following
table lists the most important node types:
91
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function windowSize(){
var w = window.innerWidth;
var h = window.innerHeight;
alert("Width: " + w + ", " + "Height: " +
h);
}
</script>
<button type="button"
onclick="windowSize();">Get Window
Size</button>
However, if you want to find out the width and height of the
window excluding the scrollbars you can use
the clientWidth and clientHeight property of any DOM
element (like a div), as follow:
Example
Try this code »
<script>
92
Rware College of Accounts
Web Design: JavaScript Training Manual
function windowSize(){
var w =
document.documentElement.clientWidth;
var h =
document.documentElement.clientHeight;
alert("Width: " + w + ", " + "Height: " +
h);
}
</script>
<button type="button"
onclick="windowSize();">Get Window
Size</button>
Note: The document.documentElement object represents
the root element of the document, which is
the <html> element, whereas the document.body object
represents the <body> element. Both are supported in all
major browsers.
Example
Try this code »
<script>
function getResolution() {
alert("Your screen is: " + screen.width +
"x" + screen.height);
}
</script>
<button type="button"
onclick="getResolution();">Get
Resolution</button>
93
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function getAvailSize() {
alert("Available Screen Width: " +
screen.availWidth + ", Height: " +
screen.availHeight);
}
</script>
<button type="button"
onclick="getAvailSize();">Get Available
Size</button>
Example
Try this code »
<script>
function getColorDepth() {
alert("Your screen color depth is: " +
screen.colorDepth);
}
</script>
<button type="button"
onclick="getColorDepth();">Get Color
Depth</button>
Tip: As of now virtually every computer and phone display
uses 24-bit color depth. 24 bits almost always uses 8 bits of
each of R, G, B. Whereas in case of 32-bit color depth, 24 bits
are used for the color, and the remaining 8 bits are used for
transparency.
94
Rware College of Accounts
Web Design: JavaScript Training Manual
For modern devices, color depth and pixel depth are equal.
Here's an example:
Example
Try this code »
<script>
function getPixelDepth() {
alert("Your screen pixel depth is: " +
screen.pixelDepth);
}
</script>
<button type="button"
onclick="getPixelDepth();">Get Pixel
Depth</button>
Example
Try this code »
<script>
function getURL() {
alert("The URL of this page is: " +
window.location.href);
}
</script>
95
Rware College of Accounts
Web Design: JavaScript Training Manual
Try out the following example to see how to use the location
property of a window.
Example
Try this code »
Example
Try this code »
<script>
function loadHomePage() {
window.location.assign("https://www.tutorialrep
ublic.com");
}
</script>
<button type="button"
onclick="loadHomePage();">Load Home
Page</button>
You can also use the replace() method to load new
document which is almost the same as assign(). The
difference is that it doesn't create an entry in the browser's
history, meaning the user won't be able to use the back
button to navigate to it. Here's an example:
96
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function loadHomePage(){
window.location.replace("https://www.tutorialre
public.com");
}
</script>
<button type="button"
onclick="loadHomePage();">Load Home
Page</button>
Alternatively, you can use the window.location.href property
to load new document in the window. It produce the same
effect as using assign() method. Here's is an example:
Example
Try this code »
<script>
function loadHomePage() {
window.location.href =
"https://www.tutorialrepublic.com";
}
</script>
<button type="button"
onclick="loadHomePage();">Load Home
Page</button>
Example
Try this code »
<script>
function forceReload() {
window.location.reload(true);
}
</script>
<button type="button"
onclick="forceReload();">Reload Page</button>
Note: The result of calling reload() method is different from
clicking browser's Reload/Refresh button.
The reload() method clears form control values that
otherwise might be retained after clicking the Reload/Refresh
button in some browsers.
97
Rware College of Accounts
Web Design: JavaScript Training Manual
You can use this property to find out how many pages a user
has visited during the current browser session, as
demonstrated in the following example:
Example
Try this code »
<script>
function getViews() {
alert("You've accessed " + history.length +
" web pages in this session.");
}
</script>
Example
Try this code »
<script>
function goBack() {
window.history.back();
}
</script>
98
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function goForward() {
window.history.forward();
}
</script>
Example
Try this code »
99
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function checkConnectionStatus() {
if(navigator.onLine) {
alert("Application is online.");
} else {
alert("Application is offline.");
}
}
</script>
<button type="button"
onclick="checkConnectionStatus();">Check
Connection Status</button>
Browser fires online and offline events when a connection is
establish or lost. You can attach handler functions to these
events in order to customize your application for online and
offline scenarios.
Example
Try this code »
<script>
function goOnline() {
// Action to be performed when your
application goes online
alert("And we're back!");
}
function goOffline() {
// Action to be performed when your
application goes offline
alert("Hey, it looks like you're
offline.");
}
100
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function checkCookieEnabled() {
if(navigator.cookieEnabled) {
alert("Cookies are enabled in your
browser.");
} else {
alert("Cookies are disabled in your
browser.");
}
}
</script>
<button type="button"
onclick="checkCookieEnabled();">Check If
Cookies are Enabled</button>
Tip: You should use
the navigator.cookieEnabled property to determine
whether the cookies are enabled or not before creating or
using cookies in your JavaScript code.
Example
Try this code »
<script>
function checkLanguage() {
alert("Your browser's UI language is: " +
navigator.language);
}
</script>
<button type="button"
onclick="checkLanguage();">Check
Language</button>
101
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function getBrowserInformation() {
var info = "\n App Name: " +
navigator.appName;
info += "\n App Version: " +
navigator.appVersion;
info += "\n App Code Name: " +
navigator.appCodeName;
info += "\n User Agent: " +
navigator.userAgent;
info += "\n Platform: " +
navigator.platform;
<button type="button"
onclick="getBrowserInformation();">Get Browser
Information</button>
Example
Try this code »
<script>
function checkJavaEnabled() {
if(navigator.javaEnabled()) {
102
Rware College of Accounts
Web Design: JavaScript Training Manual
<button type="button"
onclick="checkJavaEnabled();">Check If Java is
Enabled</button>
You can create alert dialog boxes with the alert() method.
You've already seen a lot of alert examples in the previous
chapters. Let's take a look at one more example:
Example
Try this code »
103
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
if(result) {
document.write("You clicked OK button!");
} else {
document.write("You clicked Cancel
button!");
}
Example
Try this code »
Example
Try this code »
<script>
function myFunction() {
alert('Hello World!');
}
</script>
<button onclick="setTimeout(myFunction,
2000)">Click Me</button>
The above example will display an alert message after 2
seconds on click of the button.
105
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
function showTime() {
var d = new Date();
document.getElementById("clock").innerHTML
= d.toLocaleTimeString();
}
setInterval(showTime, 1000);
</script>
This ID can be used to disable or clear the timer and stop the
execution of code beforehand. Clearing a timer can be done
using two functions: clearTimeout() and clearInterval().
Example
Try this code »
<script>
var timeoutID;
function delayedAlert() {
timeoutID = setTimeout(showAlert, 2000);
}
function showAlert() {
alert('This is a JavaScript alert box.');
}
function clearAlert() {
clearTimeout(timeoutID);
}
</script>
106
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
<script>
var intervalID;
function showTime() {
var d = new Date();
document.getElementById("clock").innerHTML
= d.toLocaleTimeString();
}
function stopClock() {
clearInterval(intervalID);
}
<button onclick="stopClock();">Stop
Clock</button>
Note: You can technically
use clearTimeout() and clearInterval() interchangeably
. However, for clarity and code maintainability you should
avoid doing so.
107
Rware College of Accounts
Web Design: JavaScript Training Manual
Well, let's get straight to it and see how this actually works.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple HTML Form</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return
validateForm()" action="confirmation.php"
method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile"
maxlength="10">
<div class="error"
id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error"
id="countryErr"></div>
</div>
108
Rware College of Accounts
Web Design: JavaScript Training Manual
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio"
name="gender" value="male"> Male</label>
<label><input type="radio"
name="gender" value="female"> Female</label>
</div>
<div class="error"
id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies
<i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox"
name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox"
name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox"
name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
Example
Try this code »
109
Rware College of Accounts
Web Design: JavaScript Training Manual
var checkboxes =
document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with
selected values
hobbies.push(checkboxes[i].value);
}
}
// Validate name
if(name == "") {
printError("nameErr", "Please enter
your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter
a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
// Validate country
if(country == "Select") {
printError("countryErr", "Please select
your country");
110
Rware College of Accounts
Web Design: JavaScript Training Manual
} else {
printError("countryErr", "");
countryErr = false;
}
// Validate gender
if(gender == "") {
printError("genderErr", "Please select
your gender");
} else {
printError("genderErr", "");
genderErr = false;
}
111
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue",
Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
112
Rware College of Accounts
Web Design: JavaScript Training Manual
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}
That's all, now open the "application-form.html" file in a web
browser and try to fill some data and see how the script
respond when an invalid data is entered in a form field.
A cookie is a small text file that lets you store a small amount
of data (nearly 4KB) on the user's computer. They are typically
used for keeping track of information such as user
preferences that the site can retrieve to personalize the page
when user visits the website next time.
document.cookie = "firstName=Christopher";
113
Rware College of Accounts
Web Design: JavaScript Training Manual
document.cookie = "name=" +
encodeURIComponent("Christopher Columbus");
document.cookie = "firstName=Christopher;
expires=Thu, 31 Dec 2099 23:59:59 GMT";
Example
Try this code »
document.cookie = cookie;
}
}
By default, a cookie is available to all web pages in the same
directory or any subdirectories of that directory. However, if
you specify a path the cookie is available to all web pages in
the specified path and to all web pages in all subdirectories of
that path. For example, if the path is set to / the cookie is
available throughout a website, regardless of which page
creates the cookie.
Further, you can use the domain attribute if you want a cookie
to be available across subdomains. By default, cookies are
available only to the pages in the domain they were set in.
114
Rware College of Accounts
Web Design: JavaScript Training Manual
Reading a Cookie
Reading a cookie is a slightly more complex because
the document.cookie property simply returns a string
containing a semicolon and a space separated list of all
cookies (i.e. name=value pairs, for example, firstName=John;
lastName=Doe;). This string doesn't contain the attributes such
as expires, path, domain, etc. that may have been set for the
cookie.
In order to get the individual cookie from this list, you need to
make use of split() method to break it into
individual name=value pairs, and search for the specific name,
as shown below:
Example
Try this code »
function getCookie(name) {
// Split cookie string and get all
individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
115
Rware College of Accounts
Web Design: JavaScript Training Manual
Example
Try this code »
function checkCookie() {
// Get cookie using our custom function
var firstName = getCookie("firstName");
if(firstName != "") {
alert("Welcome again, " + firstName);
} else {
firstName = prompt("Please enter your
first name:");
if(firstName != "" && firstName !=
null) {
// Set cookie using our custom
function
setCookie("firstName", firstName,
30);
}
}
}
Updating a Cookie
The only way to update or modify a cookie is to create
another cookie with the same name and path as an existing
one. Creating a cookie with the same name but with a
different path then that of an existing one will add an
additional cookie. Here's an example:
Example
Try this code »
// Creating a cookie
document.cookie = "firstName=Christopher;
path=/; max-age=" + 30*24*60*60;
Deleting a Cookie
To delete a cookie, just set it once again using the same name,
specifying an empty or arbitrary value, and setting its max-
age attribute to 0. Remember that if you've specified a path,
and domain attribute for the cookie, you'll also need to include
them when deleting it.
Example
Try this code »
// Deleting a cookie
116
Rware College of Accounts
Web Design: JavaScript Training Manual
117