CSS Full Notes by Rajan Sir
CSS Full Notes by Rajan Sir
Unit Outcome:
1) Create object to solve the given problem.
2) Develop javascript to implement the switch-case statement for the given problem.
3) Develop javascript to implement loop for solving the given iterative problem.
4) Display properties of the given object using getters and setters.
5) Develop program using basic features of javascript to solve the given problem.
1
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Introduction:
The scripts can be written in two forms, at the server end (back end) or at the client end
(server end). The main difference between server-side scripting and client-side scripting is
that the server-side scripting involves server for its processing. On the other hand, client-
side scripting requires browsers to run the scripts on the client machine but does not
interact with the server while processing the client-side scripts.
A script is generally a series of program or instruction, which has to be executed on other
program or application. As we know that the web works in a client-server environment. The
client-side script executes the code to the client side which is visible to the users while a
server-side script is executed in the server end which users cannot see.
Source: https://techdifferences.com/difference-between-server-side-scripting-and-
client-side-scripting.html
Server-side scripting is a technique of programming for producing the code which can run
software on the server side, in simple words any scripting or programming that can run on
the web server is known as server-side scripting.
The operations like customization of a website, dynamic change in the website content,
response generation to the user’s queries, accessing the database, and so on are performed
at the server end.
The server-side scripting constructs a communication link between a server and a client
(user). Earlier the server-side scripting was implemented by the CGI (Common Gateway
Interface) scripts. CGI was devised to execute the scripts from programming languages
such as C++ or Perl on websites.
The server-side involves four parts: server, database, API’s and back-end web software
developed by the server-side scripting language. When a browser sends a request to the
server for a webpage consisting of server-side scripting, the web server processes the
script prior to serving the page to the browser. Here the processing of a script could include
extracting information from a database, making simple calculations, or choosing the
appropriate content that is to be displayed in the client end. The script is being processed
2
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
and the output is sent to the browser. The web server abstracts the scripts from the end
user until serving the content, which makes the data and source code more secure.
The Programming languages for server-side programming are:
1) PHP
2) C++
3) Java and JSP
4) Python
5) Ruby
Client-side scripting is performed to generate a code that can run on the client end
(browser) without needing the server-side processing.
Basically, these types of scripts are placed inside an HTML document. The client-side
scripting can be used to examine the user’s form for the errors before submitting it and for
changing the content according to the user input.
In Client-side scripting, the web requires three elements for its functioning which are, client,
database and server.
The effective client-side scripting can significantly reduce the server load. It is designed to
run as a scripting language utilizing a web browser as a host program. For example, when a
user makes a request via browser for a webpage to the server, it just sent the HTML and
CSS as plain text, and the browser interprets and renders the web content in the client end.
BASIS FOR
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON
Basic Works in the back end which Works at the front end and script
could not be visible at the client are visible among the users.
end.
3
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
BASIS FOR
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON
Affect Could effectively customize the Can reduce the load to the server.
web pages and provide dynamic
websites.
4
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
● Manipulate HTML "layers" including hiding, moving, and allowing the user to drag
them around a browser window.
● Build small but complete client-side programs.
● Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)
● Displaying clocks etc.
5
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Advantages of JavaScript:
● Speed: Client-side JavaScript is very fast because it can be run immediately within
the client-side browser. Unless outside resources are required, JavaScript is
unhindered by network calls to a backend server.
● Interoperability: JavaScript plays nicely with other languages and can be used in a
huge variety of applications.
● Server Load: Being client-side reduces the demand on the website server.
Disadvantages of JavaScript:
● Security: As the code executes the user’s computer, in some cases it can be
exploited for malicious purpose.
● Javascript done not read and write the files.
● Javascript can not be used for networking applications.
● Javascript does not have multi-threading and multi-processing capabilities.
6
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
● Javascript does not support overloading and overriding.
Object Name:
Each object is uniquely identified by a name or ID.
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
7
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
In above example, person is an object and firstName , lastName and age are three
properties.
“Hhh” , “Bbb” and 10 these are values associated with properties.
Code:
<html>
<body>
<script>
emp={id:"VP-179",name:"Aaa Bbb",salary:50000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output:
VP-179 Aaa Bbb 50000
B. Define and create a single object, with the keyword “new” OR by creating instance
of Object
new keyword is used to create object.
Syntax: var objectname=new Object();
Example:
var person = new Object();
person.firstName = “Hhh";
person.age = 10;
Code:
<html>
<body>
<script>
var emp=new Object();
emp.id="VP-179";
emp.name="Aaa ";
8
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output:
VP-179 Aaa 50000
C. Define an object constructor, and then create objects of the constructed type.
Code:
<html>
<body>
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp("VP-179","Aaa ",50000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
9
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</body>
</html>
Output:
VP-179 Aaa 50000
Types of Objects:
• Native Objects/ Built-in Objects: are those objects supplied by JavaScript.
Examples of these are Math, Date, String, Number, Array, Image, etc.
1) Math:
Math Properties
Math Property Description
PI Returns Π value.
E Returns Euler's Constant.
Code:
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E;
document.write("E Value is :" + value1 + "<br>");
var value3 = Math.LN10;
document.write("LN10 Value is :" + value3 + "<br>");
var value4 = Math.PI;
document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
10
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</html>
Output:
E Value is :2.718281828459045
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793
Math Methods
Math Methods Description
Code:
<html>
<body>
<script type="text/javascript">
var value = Math.abs(-20);
document.write("ABS Value : " + value +"<br>");
var value = Math.tan(5);
document.write("TAN Value : " + value +"<br>");
</script>
</body>
</html>
Output:
ABS Value: 20
TAN Value : -3.380515006246586
11
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2) Date
Date is a data type.
Date object manipulates date and time.
Date() constructor takes no arguments.
Date object allows you to get and set the year, month, day, hour, minute, second
and millisecond fields.
Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Date Methods:
Date Methods Description
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
12
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
setMilliseconds() Sets the milliseconds.
Code:
<html>
<body>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</body>
</html>
Example:
var s = new String(string);
String Properties:
String properties Description
String Methods:
String methods Description
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
14
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
split() It splits a string object into an array of strings by separating the string
into the substrings.
Code:
<html>
<body>
<script type="text/javascript">
var str = "A JavaScript";
document.write("<b>Char At:</b> " + str.charAt(4)+"<br>");
document.write("<b>Char Code At:</b> " + str.charCodeAt(0)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf(“p")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
</body>
</html>
Output:
Char At: v
CharCode At: 65
Index of: 10
Lower Case: a javascript
Upper Case: A JAVASCRIPT
• Host Objects: are objects that are supplied to JavaScript by the browser environment.
Examples of these are window, document, forms, etc.
Window:
The window object represents a window in browser.
An object of window is created automatically by the browser.
Window is the object of browser; it is not the object of javascript.
Window Methods:
Window
methods ]Description
15
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel
button.
prompt() displays a dialog box to get input from the user along with with ok and
cancel button.
Code:
<script type="text/javascript">
function msg()
{
var a= window.prompt("Who are you?");
window.alert("I am "+a);
}
</script>
<input type="button" value="click" onclick="msg()">
Output:
16
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
• User-Defined Objects: are those that are defined by you, the programmer.
Property:
▪ Properties are the values associated with a JavaScript object.
▪ A JavaScript object is a collection of unordered properties.
▪ Properties can usually be changed, added, and deleted, but some are read only.
▪ The syntax for accessing the property of an object is:
objectName.property // person.age
objectName["property"] // person["age"]
objectName[expression] // x = "age"; person[x]
Dot Operator:
The properties and methods associated with any object can be accessed by using
dot(.) Operator.
Example, emp.id or op.add();
Dot operator is used to how to interact with objects, methods, events and properties.
Dot operator is also used to add new property.
Example, emp.designation=“Lecturer”;
Code:
<html>
<body>
<script>
var person =
{
firstname:"Hhh",
age:10
};
person.std = "Fifth"; //adding new property as “std”
document.write(person.firstname+" "+"is in "+person.std+" standard"); //Accessing
properties with dot
</script>
</body> </html>
17
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Output:
Hhh is in Fifth standard
Methods:
JavaScript methods are actions that can be performed on objects.
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function name(parameter1, parameter2, parameter3) 0p7
{
// code to be executed
}
18
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
{
firstname:"Hhh",
lastname:"Bbb",
Fullname:function() // define a function as a property
{
return this.firstname+" "+this.lastname;
}
};
document.write("Person Detail is="+person.Fullname());
</script>
Output:
Person Detail is=Hhh Bbb
Main Event:
19
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
• An HTML button was clicked
Event handlers can be used to handle, and verify, user input, user actions, and browser
actions:
Event Description
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
Code:
<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello IF5I students");
}
</script>
</head>
<body>
<center>
<p><h1>Welcome to Client-side scripting</h1></p>
<form>
<input type="button" value="click" onclick ="msg()"/> // onclick event
</form>
</body>
</html>
Output:
20
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
DOM getElementById() Method
The getElementById() method returns the elements that has given ID which is passed to
the function.
This function is widely used in web designing to change the value of any particular
element or get a particular element.
Syntax: document. getElementById(element_id) ;
Parameter: This function accepts single parameter element_id which is used to hold the ID
of element.
Return Value: It returns the object of given ID. If no element exists with given ID then it
returns null.
Code:
<html>
<body>
<p id="demo">Click the button to change the color of this paragraph.</p>
<button onclick="myFunction()">change color</button>
<script>
function myFunction()
{
var x = document.getElementById("demo");
x.style.color = "red";
}
21
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</script>
</body>
</html>
Output:
We can say that variable is a container that can be used to store value and you need
to declare a variable before using it.
In JavaScript, the var keyword is used to declare a variable. Also, starting from ES6 we can
also declare variables using the let keyword.
JavaScript Syntax for Declaring a Variable
Following is the syntax for declaring a variable and assigning values to it.
var varible-name;
or
let varible-name;
We can also define a variable without using the semicolon too. Also, when we have to
define multiple variables, we can do it like this:
var x,y,z;
or
var x,y,z
22
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
JavaScript Variable Example:
Now let's take a simple example where we will declare a variable and then assign it a value.
var emp_name;
var emp_name=”dhavan”;
● Local Variable
● Global Variable
You can use them according to the requirement in the application. Let's learn about both
JavaScript Local variables and JavaScript Global variables with examples.
23
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
A JavaScript global variable is accessible from any function.
A variable i.e. declared outside the function or declared with window object is known
as global variable.
Code:
<html>
<body>
<script>
var data=200; //gloabal variable
function a()
{
document.write(data);
}
function b()
{
document.write(data);
}
a(); //calling JavaScript function
b();
</script>
</body>
</html>
Output:
200 200
24
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Javascript let Keyword
In JavaScript, let is a keyword which is used to declare a local variable with block scope.
Unlike var keyword which declares global scope variables, with ECMAScript2016(ES6)
the let keyword was introduced to define local scope variables as defining all the variables
in global scope leads to a lot of problems while writing large JavaScript applications.
It allows you to declare limited scope variables that cannot be accessible outside of the
scope.
Let's take an example to understand the need of let keyword when we already
had var keyword to create variables in JavaScript. Suppose you are writing a big JavaScript
code which involves multiple loops, functions, and variables, as usual in all the loops you
used the same variable name for the counter which is i, and you used the var keyword to
define the variable i, now what will happen is, the variable i will carry on its changed value
throughout the whole script as it is a global variable and if you forget to re-initialize it to zero
anywhere, it will cause an error and your code will break. And you will have to put in extra
efforts to look for the error.
Whereas, if you define the counter variable i using the let keyword, its scope will be limited
to the loop only and when the first loop will end so will the counter variable. This way, using
let keyword makes more sense because we use very few global variables and many local
variables in general programming practice.
let does not create properties of the window object when declared globally.
The syntax for using the let keyword for defining a variable is the same as that of
the var keyword.
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN];
As shown in the syntax above, yes, we can use a single let keyword to define multiple
variables, but this is not new, we can do so using the var keyword too.
Let's see a few examples to see how this let keyword is used and how it works.
Use let inside a code block:
JavaScript variable declared inside a block { } cannot be accessed from outside the block, if
we have defined the variable using the let keyword. See the below example:
{
let x = 2;
}
alert(x) // not accessible
Output:
uncaught ReferenceError: x is not defined
In the above example, the variable is accessible only inside the block. See the below
example, to see that:
25
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
{
let x = 2;
alert(x) // accessible
}
Output:
2
26
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
A variable declared inside a block using var is accessible outside of the block as it has a
global scope but a variable declared using the let keyword has a local scope. Let's see an
example:
{
let amount = 2500; // block Scope
var withdraw = 2000; // global scope
}
document.write(withdraw) // accessible
document.write(amount) // not accessible
Output:
2000
Uncaught ReferenceError: amount is not defined
JavaScript const keyword is used to define constant values that cannot changed once a
value is set. The value of a constant can't be changed through reassignment, and it can't be
redeclared.
The scope of const is block-scoped it means it cannot be accessed from outside of block.
In case of scope, it is much like variables defined using the let statement.
Constants can be either global or local to the block in which it is declared. Global constants
do not become properties of the window object, unlike var variables.
Syntax
Below we have the syntax to define a constant value in JavaScript.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]
We don't have to use var or let keyword while using the const keyword. Also, we
can define a list or a simple value or a string etc as a constant.
Lets understand, how to create constant in JavaScript program. See the below example:
{
const Pi = 3.14;
alert(Pi);
Output:
3.14
27
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Let's try another example where we will try changing the value of the constant and see if
we allowed to reassign value or not.
{
const Pi = 3.14;
alert(Pi);
// Reassign value
Pi = 3.143;
alert(Pi);
}
Output:
3.14
Uncaught TypeError: Assignment to constant variable.
The scope of the variable defined using const keyword is same as that of a variable declared
using the let keyword. So, constant declared inside a block will not accessible outside of
that block. Let's take an example and see:
{
const Pi = 3.14;
alert(Pi);
}
// outside block
alert(Pi); // error
Output:
3.14
Uncaught ReferenceError: Pi is not defined
Data Types
● JavaScript provides different data types to hold different types of values.
● There are two types of data types in JavaScript:
o Primitive data type
o Non-primitive (reference) data type/ Composit Data
Types
● JavaScript is a dynamic type language; means you don't need to specify type of the
variable.
● You need to use var here to specify the data type.
● It can hold any type of values such as numbers, strings etc.
● For example: var a=40;//holding number
● var b=“Info Technology”//holding string
28
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
JavaScript Data Types
✔ The undefined data type can only have one value-the special value “undefined”.
29
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
✔ If a variable has been declared, but has not been assigned a value, has the
value ”undefined”.
✔ Example,
var a;
var b = “Welcome”;
alert(a) // Output: undefined
alert(b) // Output: Welcome
✔ An array is a type of object used for storing multiple values in single variable.
✔ Each value (also called an element) in an array has a numeric position, known as its
index, and it may contain data of any data type-numbers, strings, Booleans,
functions, objects, and even other arrays.
30
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
✔ The array index starts from 0, so that the first array element is arr [0].
✔ The simplest way to create an array is by specifying the array elements as a
comma-separated list enclosed by square brackets, as shown in the example
below:
✔ var cities = ["London", "Paris", "New York"];
✔ alert(cities[2]); // Output: New York
✔ var a = ["London", 500, ”aa56”, 5.6];
31
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Types of Literals:
● Array Literal
● Integer Literal
● Floating number Literal
● Boolean Literal (include True and False)
● Object Literal
● String Literal
Array Literal:
● an array literal is a list of expressions, each of which represents an array element,
enclosed in a pair of square brackets ' [ ] ‘ .
● When an array is created using an array literal, it is initialized with the specified
values as its elements, and its length is set to the number of arguments specified.
● Creating an empty array :
var tv = [ ];
Creating an array with four elements.
var tv = [“LG", “Samsung", “Sony", “Panasonic"]
✔ Comma in array literals:
● In the following example, the length of the array is four, and tv[0] and tv[2] are
undefined.
● var tv = [ , “Samsung“, , “Panasonic"]
● This array has one empty element in the middle and two elements with values.
( tv[0] is “LG", tv[1] is set to undefined, and tv[2] is “Sony")
Var tv = [“LG", ,“Sony", ]
Integer Literal:
An integer must have at least one digit (0-9).
• No comma or blanks are allowed within an integer.
• It does not contain any fractional part.
• It can be either positive or negative if no sign precedes it is assumed to
be positive.
In JavaScript, integers can be expressed in three different bases.
1. Decimal ( base 10)
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be
no leading zeros.
Example: 123, -20, 12345
32
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2. Hexadecimal ( base 16)
Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters
A, B, C, D, E, F or a, b, c, d, e, f.
A leading 0x or 0X indicates the number is hexadecimal.
Example: 7b, -14, 3039
3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the
number is octal.
Example: 0173, -24, 30071
Floating number Literal:
A floating number has the following parts.
• A decimal integer.
• A decimal point ('.').
• A fraction.
• An exponent.
The exponent part is an "e" or "E" followed by an integer, which can be signed
(preceded by "+" or "-").
Example of some floating numbers:
• 8.2935
• -14.72
• 12.4e3 [ Equivalent to 12.4 x 103]
• 4E-3 [ Equivalent to 4 x 10-3 => .004]
Object Literal:
An object literal is zero or more pairs of comma-separated list of property names and
associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
var userObject = { }
33
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
• There will be no comma after the last property name/value pair.
String Literal:
● JavaScript has its own way to deal with string literals.
● A string literal is zero or more characters, either enclosed in single quotation (')
marks or double quotation (") marks. You can also use + operator to join strings.
● The following are the examples of string literals:
⮚ string1 = "w3resource.com"
string1 = 'w3resource.com’
⮚ string1 = "1000“
● In addition to ordinary characters, you can include special characters in strings, as
shown in the following.
⮚ string1 = "First line. \n Second line."
Special characters in JavaScript:
character Description
\’ Single quote
\” Double quote
\\ Backslash
\b Backspace
\f Form Feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
Comments in JavaScript:
The JavaScript comments are meaningful way to deliver message.
34
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
It is used to add information about the code, warnings or suggestions so that end user
can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
There are two types of comments in JavaScript.
1. Single-line Comment
It is represented by double forward slashes (//).
It can be used before and after the statement.
Example,
<script>
// It is single line comment
document.write("hello javascript");
</script>
2. Multi-line Comment
It can be used to add single as well as multi line comments.
It is represented by forward slash with asterisk then asterisk with forward slash.
Example,
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
+ Addition 10+20 = 30
35
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
- Subtraction 20-10 = 10
/ Division 20/10 = 2
% Modulus 20%10 = 0
Code:
<html>
<body>
<script type = "text/javascript">
var a = 33;
var b = 10;
var c = "Test";
document.write("a + b = ");
result = a + b;
document.write(result+"<br>");
document.write("a - b = ");
result = a - b;
document.write(result+"<br>");
document.write("a / b = ");
result = a / b;
document.write(result+"<br>");
36
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.write("a % b = ");
result = a % b;
document.write(result+"<br>");
document.write("a + b + c = ");
result = a + b + c;
document.write(result+"<br>");
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result+"<br>");
b = --b;
document.write("--b = ");
result = --b;
document.write(result+"<br>");
</script>
</body>
</html>
Output:
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8 Operators: compares the two operands
2) Comparison (Relational)
37
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
== Is equal to 10==20 = false
Code:
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = 20;
38
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.write("(a >= b) => ");
result = (a >= b);
document.write(result+"<br>");
39
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
>>> Bitwise Right Shift (10>>>2) = 2
with Zero
Code:
<html>
<body>
<script type="text/javascript">
40
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</script>
</body>
</html>
Output:
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
4) Logical Operator:
Code:
<html>
<body>
<script type = "text/javascript">
var a = true;
var b = false;
41
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.write("(a || b) => ");
result = (a || b);
document.write(result+"<br>");
42
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
5) Assignment Operator:
= Assign 10+10 = 20
Code:
<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
43
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
result = (a += b);
document.write(result+"<br>");
Output:
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
44
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
6) Special Operator:
Operator Description
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = "Information";
var c= function(x)
{
return x*x;
}
45
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.write(typeof b+"<br>"); // b="Information" is a string
document.write(typeof c+"<br>"); // c= function
document.write(c(4));
</script>
</body>
</html>
number
string
function
16
Output:
46
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
The below table shows the precedence and associativity of operators. In this table,
precedence is from bottom to top i.e items at the bottom having low precedence and
precedence increases as we move to the top of the table.
. left-to-right
member
[]
increment ++
decrement --
logical-not ! right-to-left
unary + + right-to-left
47
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Operator type Operator (Symbol) Associativity
in in left to right
48
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Operator type Operator (Symbol) Associativity
Expression:
Any unit of code that can be evaluated to a value is an expression.
Since expressions produce values, they can appear anywhere in a program where
JavaScript expects a value such as the arguments of a function invocation.
Types of Expression:
49
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
1. Primary Expression:
Primary expressions refer to stand alone expressions such as literal values, certain
keywords and variable values.
'hello world'; // A string literal
23; // A numeric literal
true; // Boolean value true
sum; // Value of variable sum
this; // A keyword that evaluates to the current object.
Example:
emp.firstName;
emp[lastName];
50
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Function expressions are evaluated only when the interpreter reaches the line of code
where function expressions are located.
Example:
var sq=function (x)
{ return x*x;
}
5. Invocation Expression
An invocation expression is JavaScript’s syntax for calling (or executing) a function or
method.
It starts with a function expression that identifies the function to be called.
The function expression is followed by an open parenthesis, a comma-separated list
of zero or more argument expressions, and a close parenthesis.
When an invocation expression is evaluated, the function expression is evaluated first,
and then the argument expressions are evaluated to produce a list of argument values.
Example,
f(0) // f is the function expression; 0 is the argument expression
Math.max(x,y,z) // Math.max is the function; x, y and z are the
arguments.
51
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
1) if statement:
Use if statement to specify a block of JavaScript code to be executed if a condition is true.
\Syntax:
Example:
<html>
<body>
<script>
document.write("Good day!");
</script>
</body>
</html>
52
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2) The else Statement
Use else statement to specify a block of code to be executed if the condition is false.
Syntax:
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:
<html>
<body>
<script>
if (new Date().getHours() < 18)
{
document.write("Good day!");
}
else
{
document.write("Good Evening!");
}
</script>
</body>
</html>
Syntax:
53
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
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:
<html>
<body>
<script>
var greeting;
var time = new Date().getHours();
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
document.write(greeting);
</script>
</body>
</html>
4) The switch case Statement
The switch statement is used to perform different actions based on different
conditions. It is used to select one of many code blocks to be executed.
Syntax:
switch(expression)
{ 54
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
case x:
// code block
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values
of each case.
If there is a match, the associated block of code is
executed.
If there is no match, the default code block is executed.
Example:
<html>
<body>
<script>
var day;
switch (new Date().getDay())
{
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
day = "Thursday";
break;
case 5:
day = "Friday";
break;
55
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
case 6:
day = "Saturday";
}
document.write("Today is " + day);
</script>
</body>
</html>
default keyword:
default keyword specifies the code to run if there is no case match.
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.
Example:
switch (new Date().getDay())
{
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
Example:
<html>
<body>
<script>
// program for a simple calculator
var result;
56
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
// take the operand input
var number1 = parseFloat(prompt('Enter first number: '));
var number2 = parseFloat(prompt('Enter second number: '));
switch(operator)
{
case '+':
result = number1 + number2;
document.write(`${number1} + ${number2} = ${result}`);
break;
case '-':
result = number1 - number2;
document.write(`${number1} - ${number2} = ${result}`);
break;
case '*':
result = number1 * number2;
document.write(`${number1} * ${number2} = ${result}`);
break;
case '/':
result = number1 / number2;
document.write(`${number1} / ${number2} = ${result}`);
break;
default:
document.write('Invalid operator');
break;
}
</script>
</body>
</html>
Output:
57
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
1.7 JavaScript Loop Statement
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
58
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
1) for loop
✔ The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known.
Syntax:
Example:
<script>
for (i=0; i<=10; i=i+2)
{
document.write(i + "<br/>")
}
</script>
2) do while Loop
loop is a variant of the while loop.
This loop will execute the code block once.
before checking if the condition is true, then it will repeat the loop as long as the condition
is true.
Syntax:
do
{
code to be executed
}
while (condition);
Example:
59
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<script>
var i=21;
do{
document.write(i +"<br/>");
i++;
}while (i<=25);
</script>
3) while loop
The JavaScript while loop loops through a block of code as long as a specified
condition is true.
Syntax:
while (condition)
{
Code to be executed
}
Example:
<script>
var i=11;
while (i<=20)
{
document.write(i + "<br/>");
i++;
}
</script>
4) for-in loop
The for/in statement loops through the properties of an object.
The block of code inside the loop will be executed once for each property.
Syntax:
Example:
60
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<script type = "text/javaScript">
var lang = { first : "C", second : "Java",third : "Python", fourth : “PHP"};
for (prog in lang)
{
document.write(lang[prog] + "<br >");
}
</script>
Output:
C
Java
Python
PHP
61
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Difference between While Loop and Do – While Loop
In while loop, first it checks the condition In Do – While loop, first it executes the
and then executes the program. program and then checks the condition.
The condition will come before the body. The condition will come after the body.
If the condition is false, then it terminates It runs at least once, even though the
the loop. conditional is false.
break statement
break statement breaks the loop and continues executing the code after the loop.
The break statement can also be used to jump out of a loop.
Example:
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 5
The number is 6
1.8 Querying and Setting Properties
To obtain the value of a property, use . (dot) operator or square[ ] bracket.
The left-hand side should be an expression whose value is an object.
If using dot (.) operator, the right-hand must be a simple identifier that names the
property.
If using square brackets, the value within the brackets must be an expression that
evaluates to a string that contains the desired property name.
Example,
var name=author.lastname; //get the “lastname ” property of the book
var title=book[“main title”]; //get the “main title” property of the book
To create or set a property, use a dot or square brackets as you would to query the
property, but put them on the left-hand side of an assignment expression:
Example,
63
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
book.price=250; //create or set a property of price
book[“main title”]=“JavaScript” //set the “main title” property
Deleting properties:
The delete operator deletes a property from an object.
The delete operator deletes both the value of the property and the property itself.
Syntax:
delete var_name.property;
<html>
<body>
<script>
var a={name:"Priti",age:35};
document.write(a.name+" "+a.age+"<br>");
delete a.age; //delete property
document.write(a.name+" "+a.age);
</script>
</body>
</html>
Output:
Priti 35
Priti undefined
Property getter and setter
Also known as Javascript assessors.
Getters and setters allow you to control how important variables are accessed and
updated in your code.
JavaScript can secure better data quality when using getters and setters.
64
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
}
};
document.write(person.fullName());
</script>
65
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Code: Getters and setters allow you to get and set properties via methods.
<script>
var person = {
firstName: 'Chirag',
lastName: 'Shetty',
get fullName()
{
return this.firstName + ' ' + this.lastName;
}, Output:
set fullName (name) Chirag Shetty
{ before using set fullname()
var words = name.split(' '); YASH Desai
this.firstName = words[0];
this.firstName = words[0].toUpperCase();
this.lastName = words[1];
}
}
document.write(person.fullName); //Getters and setters allow you to get and set
properties via methods.
document.write("<br>"+"before using set fullname()"+"<br>");
person.fullName = 'Yash Desai'; //Set a property using set
document.writeln(person.firstName); // Yash
document.write(person.lastName); // Desai
</script>
66
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Unit 2
Array, Function and String
Marks: 14 (R-2, U-4, A-8)
Unit Outcome:
2.1 Array-Declaring an array, initializing an array, defining an array element, looping an array,
adding an array element, sorting an array element, combining an array element into a string,
changing elements of an array, Objects as Associative array.
2.3 Calling a function- calling a function with or without an argument, calling function from
HTML, function calling another function, returning the value from a function.
2.4 String- manipulate a string, joining a string, retrieving a character from given position,
retrieving a position of character in a string, dividing a text, copying a sub-string, converting
string to number and numbers to string, changing the case of string, finding Unicode of a
character.
1
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2. Introduction
2.1 Array
● Array is used to store a set of values (different types) in a single variable name.
● Arrays are the fundamentals part of most programming languages and scripting
languages.
● Using array, we can store multiple values under a single name.
In JavaScript, objects and array are handled almost identically, because arrays are merely
a special kind of object.
You can declare an array with the “new” keyword to instantiate the array in memory.
This method is creating an empty array with no elements and is equivalent to the array literal
[].
C. Explicitly specify two or more array elements or a single non-numeric element for the
element for the array:
In this form, the constructor arguments become the elements of the new array.
When we declare array using square brackets is called the “array literal notation”:
Var x= [];
Var x=[5];
When initializing an array, you place the value within the parentheses of the Array()
constructor.
The following example initializes the products array with the value 'BMW', which is assigned
to the first element of this array:
In the real world, an array usually has more than one array element, with each
element having its own value. Therefore, you’ll find yourself having to initialize the array
with more than one value.
Here’s how this is done:
var products = new Array('BMW', 'Maruti', 'Mahindra')
while Initializing array with declaration then all elements must specify in parenthesis and
elements should be separated by a comma.
Code:
<html>
<head>
<title>Array</title>
</head>
3
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<body>
<script>
var products = new Array('BMW', 'Maruti', 'Mahindra');
document.write(“Length of array is :”+products.length);
</script>
</body>
</html>
Output:
Length of array is : 3
Array is used to store a set of values in a single variable name. In order to differentiate
between these set of values. Array make use of index.
cars[0] = “BMW”;
cars[1] = “Maruti”;
cars[2] =2546 ;
As JavaScript automatically changes the value of length when you add elements to an array
that you created with the Array keyword. Array indicates in JavaScript always start at 0 , not
1, so the length property is always one greater than the largest index in the array.
Accessing an array value is quite easy. We use array index to access a value. If we want to
access val 1 from the above syntax , we use Array[0], So,
Code:
<html>
<head>
<title> Array</title>
</head>
4
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<body>
<script>
var cars = new Array(3);
cars[0] = “BMW”;
cars[1]=”Maruti”;
cars[2]=”Honda”;
document.write(cars[0]);
document.write(“<br>”+ cars[1]);
document.write(“<br>”+ cars[2]);
</script>
</body></html>
Output:
BMW
Maruti
Honda
5
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2.1.4 Looping an Array
Loops are handy, if you want to run the same code over and over again, each time with a
different value. We can use arrays within loops and access array elements using loops in
JavaScript.
To identify how many loops, we must know the total number of elements present inside the
array which can find out using array_name.length.
Example:
<html>
<body>
<h2>JavaScript For Loop</h2>
<script>
var cars = ["BMW", "Volvo", "Ford", "Fiat"];
var text = "";
var i;
for (i = 0; i < cars.length; i++)
{
document.write(cars[i]+"<br>");
}
</script>
</body>
</html>
Output:
BMW
Volvo
Ford
Fiat
6
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2.1.4 Adding an Array Element
On some occasions your JavaScript will need to increase the size of the array while your
JavaScript is running.
There are two methods to add the elements into the array:
Method1:
The easiest way to add a new element to an array is using the push() method.
The push() method adds new items to the end of an array, and returns the new length.
Syntax:
array.push(item1, item2, ..., itemX);
Example:
var fruits = [ "Banana", "Orange", "Apple", "Mango” ];
fruits.push( "Lemon” ); // adds a new element (Lemon) to fruits
Method 2:
The unshift() method adds one or more elements to the beginning of an array and returns
the new length of the array.
.
Syntax:
array.unshift(item1, item2, ..., itemX);
Example:
var fruits = [ "Banana", "Orange", "Apple", "Mango” ];
fruits.unshift( "Lemon","Pineapple” );
Example:
<html>
<head>
<title> Array</title>
<body>
<script>
var fruits = new Array(3);
fruits[0] = "Banana";
fruits[1] = "Orange";
fruits[2] = "Apple";
fruits[3] = "Mango";
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i] +" "+"<br>");
}
7
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
fruits.push("Lemon");
fruits.unshift("Pineapple");
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i] +" ");
}
</script>
</body>
</html>
Output
The index of the array elements determines the order in which values appear in an array
when a for loop is used to display the array. Sometimes you want values to appear in sorted
order, which means that strings will be presented alphabetically and numbers will be
displayed in ascending order. You can place an array in sorted order by calling the sort()
method of the array object. the index of the element to which the value is assigned.
Here’s what you need to do to sort an array:
1. Declare the array.
2. Assign values to elements of the array.
3. Call the sort() method.
Example:
<html>
<body>
<script>
8
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
var products = new Array();
products[0] = 'Soap ';
products[1] = 'Water';
products[2] = 'Pizza';
products[3] = 'Fan';
products.sort();
for (var i = 0; i < products.length; i++)
{
document.write(products[i] + '<br>');
}
</script>
</body>
</html>
Output:
Fan
Pizza
Soap
Water
Example:
<html>
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange", "Apple"];
fruits.sort();
document.write(fruits+"<br>");
fruits.reverse();
9
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.write(fruits+"<br>");
</script>
</body>
</html>
Output:
Apple,Banana,Chikoo,Mango,Orange,Watermelon
Watermelon,Orange,Mango,Chikoo,Banana,Apple
car[0] = “BMW”;
car[1] = “Maruti”;
car[2] = “Honda”;
The concat() method separates each value with a comma. It is used to join one or more
arrays.
Syntax:
array.concat()
Example:
var CO_Subject = ["PHP", "CSS", "Java"];
var Math_Subject= ["Applied Math", "Elements of Maths"];
var subjects = CO_Subject.concat(Math_Subject);
document.write(subjects);
Output:
PHP,CSS,Java,Applied Math,Elements of Maths
10
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
● The array.join() method is an inbuilt function in JavaScript which is used to join the
elements of an array into a string.
● The elements of the string will be separated by a specified separator and its default
value is comma( , ).
Syntax: array.join(separator);
Parameters: *
Separator: It is Optional.
it can be either used as parameter or not. Its default value is comma(, ).
Example:
<html>
<body>
<script>
Car,Water,Soap,Pizza
11
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2.1.8 Changing Elements of an Array:
The shift() method removes the first element of the array then moves the other tasks up on
the list and returns the removed item.
Example:
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
Var car = new Array(3);
car[0]=”BMW”;
car[1]=”Honda”;
car[2]=”Maruti”;
car.shift();
for (i=0;i<car.length;i++)
{
document.write(items[i]+””);
}
</script>
</body>
</html>
Output:
Honda Maruti
12
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
The pop() method remove an item from the end of an array
Example:
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
Var car = new Array(3);
car[0]=”BMW”;
car[1]=”Honda”;
car[2]=”Maruti”;
car.pop();
for (i=0;i<car.length;i++)
{ document.write(items[i]+””);
}</script>
</body>
</html>
Output:
BMW Honda
The splice() method can be used to add new items to an array, and removes elements from
an array.
Syntax: arr.splice(start_index,removed_elements,list_of_elemnts_to_be_added);
Parameter:
•The first parameter defines the position where new elements should be added (spliced in).
•The second parameter defines how many elements should be removed.
•The list_of_elemnts_to_be_added parameter define the new elements to be
added(optional).
Example:
<html>
13
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange", "Apple"];
document.write(fruits+"<br>");
fruits.splice(2,2, "Lemon", "Kiwi");
document.write(fruits+"<br>");
fruits.splice(0,2); //removes first 2 elements from array document.write(fruits+"<br>");
</script>
</body>
</html>
Output:
Banana,Watermelon,Chikoo,Mango,Orange,Apple
Banana,Watermelon,Lemon,Kiwi,Orange,Apple
Lemon,Kiwi,Orange,Apple
The slice() method slices out a piece of an array into a new array.
Parameter:
•slices out a part of an array starting from array element 1.
Example:
<html>
<body>
<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
document.write(fruits);
var citrus = fruits.slice(2);
document.write("<br>"+citrus);
</script>
</body>
</html>
Output:
14
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Banana,Orange,Lemon,Apple,Mango
Lemon,Apple,Mango
● Thus, the following two JavaScript expressions have the same value:
object.property ;
object["property"] ;
objectName["propertyName" ] ;
Example:
<html>
<body>
<script>
var object1 = new Object;
object1.name = “abc";
object1.nationality = "Indian";
document.write(" property name: " + object1["name"] );
document.write("<br>");
document.write(" property nationality: " + object1["nationality" ] );
</script>
</body>
</html>
OUTPUT :
property name: Girija
property nationality: Indian
15
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Sr. No. Methods Description
1 concat Returns a new array consisting of a combination of
two array
2 indexOf Returns the index of the first occurrence of a value in
an array.
3 Join Joins all elements of an array into a string
4 lastIndexOf Returns the index of the last occurrence of a specified
value in an array
5 Pop Removes the last element of an array
6 Push Add new elements to the end of an array and returns
the new length
7 Reverse Reverses the order of the elements in an array
8 Shift Removes the first element of an array and return that
element
9 Slice Selects a part of an array, and returns the new array
10 Sort Sorts the elements of an array
11 Splice Adds/Remove elements from array
12 toString Converts an array to a string, and returns the result
13 unshift Adds new element at the beginning of an array
14 valueOf Returns the primitive value of an array
<html>
<body>
<script>
var arr = new Array();
arr.push(1,2,3);
arr.push(5,6);
document.write("After the Join method" +arr.join(","));
arr.pop();
document.write("<br>After the pop method" +arr.join(","));
arr.shift();
document.write("<br>After the shift method" +arr.join(","));
arr.reverse();
document.write("<br>After the reverse method"+arr.join(","));
arr.unshift(1);
document.write("<br>After the unshift method" +arr.join(","));
16
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</script>
</body>
</html>
Output:
2-Dimensional Array:
The two-dimensional array is a collection of items which share a common name and they
are organized as a matrix in the form of rows and columns.
Example:
var branch = [
['Computer Engg', "CO"],
['Information Technology', "IF"],
['Electronics and Telecommunication', "EJ"] ];
<script>
var branch = [
['Computer Engg', "CO"],
['Information Technology', "IF"],
['Electronics and Telecommunication', "EJ"],
['Civil Engineering', "CV"],
['Chemical Engg', "CE"],
['Instrumnet Engg',"IE"]
];
// display now
17
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
for(i = 0; i < branch.length; i++)
document.write(branch[i][0] + ',' + branch[i][1] + '<br>' );
</script>
Output:
Computer Engg,CO
Information Technology,IF
Electronics and Telecommunication,EJ
Civil Engineering,CV
Chemical Engg,CE
Instrumnet Engg,IE
Multi-Dimensional Array:
Multidimensional arrays are not directly provided in JavaScript. If we want to use anything
which acts as a multidimensional array then we need to create a multidimensional array by
using another one-dimensional array. So multidimensional arrays in JavaScript is known as
arrays inside another array. We need to put some arrays inside an array, then the total thing
is working like a multidimensional array. The array, in which the other arrays are going to
insert, that array is use as the multidimensional array in our code. To define a
multidimensional array, its exactly the same as defining a normal one-dimensional array.
Example:
<script>
var my_ans = new Array(); // declaring array
my_ans.push({0:45,1:55,2:65,3:45});
my_ans.push({0:145,1:155,2:165,3:"VP"});
my_ans.push({0:245,1:255,2:265});
my_ans.push({0:"aaa",1:"bbb",2:"ccc",3:"ddd"});
18
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
for(i=0;i<4;i++)
{
document.write("key : " + i + " =>value: " + my_ans[i][0] +
',' +my_ans[i][1] + ',' +my_ans[i][2]+ ',' +my_ans[i][3] + "<br>");
}
</script>
Output:
2.2 Function
Functions are building blocks of any programming language. Function is a block of
statements that perform certain tasks.
1. Built-in functions are the functions that are already defined in JavaScript. Examples are
written (), prompt () etc.
Function Name
19
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
The function name is the name that you’ve assigned the function. It is placed at the
top of the function definition and to the left of the parentheses. Any name will do,
as long as it follows certain naming rules. The name must be
● Letter(s), digit(s), or underscore character
● Unique to JavaScript on your web page, as no two functions can have the
same name
Parentheses
● Parentheses are placed to the right of the function name at the top of the function
definition.
● Parentheses are used to pass values to the function; these values are
called arguments.
Code Block
● The code block is the part of the function definition where you insert JavaScript
statements that are executed when the function is called by another part of your
JavaScript application.
● Open and close French braces define the boundaries of the code block. Statements
that you want executed must appear between the open and close French braces.
Return (Optional)
● The return keyword tells the browser to return a value from the function definition
to the statement that called the function.
function function_name(parameters…)
{
Statements ….
20
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
}
Example:
function hellojavascript()
{
alert(“hello”);
}
● A function typically needs data to perform its task. Sometimes you provide the data
when you define the function, such as the salary and percentage increase in salary
instead of writing this data into the function definition.
● Other times, the data is known only when you run your JavaScript.
● For example, we could ask the user to enter the salary and percentage
increase in salary instead of writing this data into the function definition.
● Data that is needed by a function to perform its task that is not written into the
function definition must be passed to the function as an argument.
● An argument is one or more variables that are declared within the parentheses of a
function definition.
Syntax:
Example:
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName)
{
alert("Hello " + firstName + " " + lastName)
}
ShowMessage("Steve", "Jobs");
21
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</script>
</body>
</html>
● The scope of a variable means how the different parts of the program can access
that variable. In JavaScript there are two types of Scope namely: Local Scope and
Global Scope.
● A variable can be declared within a function this is called a local variable, because
the variable is local to the function. Other parts of your JavaScript don’t know that
the local variable exists because it’s not available outside the function.
● But a variable can be declared outside a function. Such a variable is called a
● global variable because it is available to all parts of your JavaScript—that is,
statements within any function and statements outside the function can use a global
variable.
● JavaScript developers use the term scope to describe whether a statement of a
JavaScript can use a variable. A variable is considered in scope if the statement can
access the variable. A variable is out of scope if a statement cannot access the
variable.
function myFunction()
{
// code here can also use carName
}
22
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2.3 Calling a Function
● You call a function any time that you want the browser to execute statements
contained in the code block of the function.
● A function is called by using the function name followed by parentheses. If the
function has arguments, values for each argument are placed within the
parentheses.
● You must place these values in the same order that the arguments are listed in the
function definition. A comma must separate each value.
● Here is an example of how to define and call a function that does not have any
arguments.
● The function definition is placed within the <head> tag and the function call is placed
within the <body> tag.
● When the function is called, the browser goes to the function definition and executes
statements within the code block of the function.
Example:
<html>
<body>
<script>
function IncreaseSalary()
{
var salary = 500000 * 1.25;
alert('Your new salary is ' + salary);
}
IncreaseSalary();
</script>
</body>
</html>
23
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Output:
● The Salary and Increase variables are then used within the parentheses of
the function call, which tells the browser to assign these values to the corresponding
arguments in the function definition. The function calculates and displays the new
salary.
Example:
<html>
<body>
<script>
function IncreaseSalary(OldSalary, PercIncrease)
{
var NewSalary =
OldSalary * (1 + (PercIncrease / 100))
alert("Your new salary is " + NewSalary)
}
var Salary = prompt('Enter old salary.', ' ')
var Increase =
prompt('Enter salary increase as percent.', ' ')
IncreaseSalary(Salary, Increase)
</script>
</body>
</html>
24
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Output:
● A function can be called from HTML code on your web page. Typically, a function
will be called in response to an event, such as when the web page is loaded or
unloaded by the browser.
● You call the function from HTML code nearly the same way as the function is called
from within a JavaScript, except in HTML code you assign the function call as a
value of an HTML tag attribute.
<html>
<script >
25
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
function WelcomeMessage()
{
alert('Glad to see you.')
}
function GoodbyeMessage()
{
alert('So long.')
}
</script>
<body onload="WelcomeMessage()"
onunload="GoodbyeMessage()">
</body>
</html>
Output:
26
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
JavaScript developers typically divide an application into many functions, each of
which handles a portion of the application.
<html>
<head>
<title> function calling another function </title>
<script>
function Logon()
{
var userID;
var password;
var valid;
userID=prompt('Enter user ID', ' ');
password=prompt('Enter Password', ' ');
valid=validateLogon(userID, password);
if(valid === true)
{
alert("Valid Logon");
}
else
{
alert("InValid Logon");
}
}
function validateLogon(id, pwd)
{
var ret_val;
if(id === '111' && pwd === 'aaa')
{
ret_val=true;
}
else
{
ret_val=false;
}
return ret_val;
27
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
}
</script>
</head>
<body onload="Logon()">
</body>
</html>
Output:
..
28
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
● A function can be designed to do something and then report back to the statement
that calls after it’s finished
● A function reports back to the statement that calls the function by returning a value
to that statement using the return keyword, followed by a return value in a
statement.
<html>
<bod>
<script>
var x = myFunction(4, 3);
function myFunction(a, b)
{
return a * b;
}
document.write(x);
</script>
</body>
</html>
Output:
12
2.4 String
A) By string literal:
Syntax:
29
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
var stringname=new String("string literal");
In JavaScript there are various properties and methods associated with string objects.
String Properties:
<html>
<head>
<title>JavaScript String constructor Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String();
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
30
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Output:
<html>
<body>
<h1>without using prototype property</h1>
<script>
function Student()
{
this.name = 'Pallavi';
this.gender = 'F';
}
<html>
31
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<body>
<h1>Prototype</h1>
<script>
function Student()
{
this.name = 'Pallavi';
this.gender = 'M';
}
Student.prototype.age = 20;
var studObj1 = new Student();
document.write(studObj1.age+"<br>");
var studObj2 = new Student();
document.write(studObj2.age);
</script>
</body>
</html>
Output:
String Methods:
Methods Description
charAt() It provides the char value present at the specified index
charCodeAt() It provides the Unicode value of a character present at the
specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string
by searching a character from the last position.
32
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
search() It searches a specified regular expression in a given string and
returns its position if a match occurs.
match() It searches a specified regular expression in a given string and
returns that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the
specified index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toUowerCase() It converts the given string into uppercase letter.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly
created array.
trim() It trims the white space from the left and right side of the string.
● When you concatenate a string, you form a new string from two strings by placing a
copy of the second string behind a copy of the first string.
● The new string contains all the characters from both the first and second strings.
● You use the concatenation operator (+) to concatenate two strings, as shown here
<html>
<bod>
<script>
var s1="Rahul";
var s2="Patil";
33
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
var s3=s1.concat(s2);
document.write(s3);
var s4=s1+s2;
document.write("<br>"+s4);
</script>
</body>
</html>
Output:
RahulPatil
RahulPatil
Output:
34
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
<html>
<body>
<script>
var s1="JavaScript is a scripting language";
var n=s1.indexOf("a");
document.writeln(n+"<br>");
document.writeln(s1.search("scripting"));
var m=s1.lastIndexOf("a");
document.writeln("<br>"+m);
</script>
</body>
</html>
Output:
1
16
31
● The split() method creates a new array and then copies portions of the string, called
a substring, into its array elements.
● You must tell the split() method what string (delimiter) is used to separate substrings
in the string.
● You do this by passing the string as an argument to the split() method.
<html>
<body>
<script>
var str="CO IF EJ";
document.write(str.split(" "));
</script>
</body>
</html>
Output:
CO,IF,EJ
35
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
2.4.6 Copying a Substring:
● Now you’ve learned how to divide a string into many substrings by using the
split() method and a string called a delimiter.
● This is useful when you are separating a string containing data elements into
individual data elements.
● However, the split() method isn’t of much use to you if you need to copy one
substring.
● For this, you’ll need to use one of two other methods: substring() and substr().
1. The substring()is a method of a string object that copies a substring from a string
based on a beginning and an end position that is passed as an argument to the substring()
method.
Syntax:
String.substring(startindex, endindex);
2. In the real world, you probably won’t know the starting position and end position of
characters for your substring, because a user can enter any length string into your
application. You can overcome this problem by using the substr() method The substr()
method returns a substring. You must tell it the starting position of
the first character that you want to include in the substring and how many characters you
want copied into the substring from the starting position. Both positions are passed as
arguments to the substr() method.
Syntax:
String.substr(startindex,length);
<html>
<body>
<script>
var str="JavaScript";
document.write(str.substr(0,6));
document.write("<br>");
document.writeln(str.substring(4,9));
</script>
</body>
</html>
Output:
36
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
JavaSc
Scrip
● If you need to convert string values to number values, you can do so by converting
a number within a string into a numeric value that can be used in a calculation.
● You do this by using the parseInt() method and parseFloat() method of the string
object. The parseInt() method converts a number in a string to an integer numeric
value, which is a whole number. You write the parseInt() method this way:
var num = parseInt(StringName)
● The parseFloat() method is used similarly to the parseInt() method, except the
parseFloat() method is used with any number that has a decimal value.
● Number( ): converts a string into number.
<html>
<body>
<script>
var a=50;
var b="67";
var c="45.75";
var ans=a + parseInt(b)+parseFloat(c);
document.write("Addition="+ans);
var sum=a+ Number(b)+parseFloat(c);
document.write("<br>"+"SUM="+sum);
</script>
</body>
</html>
Output:
Addition=162.75
SUM=162.75
37
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
● As you can probably guess, you need to convert a numeric value to a string before
the number can be used in the string.
● You do this by calling the toString() method of the number object.
● The toString() method can be used to convert both integers and decimal values
(floats).
● Here’s how to convert a number value to a string:
Var NumCount = 100
var StrCount = NumCount.toString()
<html>
<body>
<script>
var a=50;
var b=80;
var ans=a + b.toString();
document.write("Addition="+ans);
</script>
</body>
</html>
Output:
Addition=5080
1. toLowerCase(): this method converts all the string character to lowercase.It does not
take any argument.
2.toUpperCase(): this method converts all the string character to uppercase. It does not
take any argument.
<html>
<body>
<script>
var str = "JavaScript";
38
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
document.writeln(str.toLowerCase());
document.writeln("<br>"+str.toUpperCase());
</script>
</body>
</html>
Output:
javascript
JAVASCRIPT
<html>
<body>
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
document.write("<br>");
var res = String.fromCharCode(72, 69, 76, 76, 79);
var res1 = String.fromCharCode(73, 70, 77, 77, 80);
document.write(res);
document.write("<br>"+res1);
39
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
</script>
</body>
</html>
Output:
97
HELLO
IFMMP
Code:charCodeAt()
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
Output:
97
<script>
var str="JavaProgramming";
document.writeln(str.replace("Programming","Script"));
</script>
Output:
JavaScript
The search() method searches a string for a specified value, and returns the
position of the match.
<script>
var str="JavaScript is a scripting language.";
document.writeln(str.search("scripting"));
</script>
Output:
16
The string.match() is an inbuilt function in JavaScript which is used to search a string for a
match against an any regular expression and if the match will found then this will return
the match as an array otherwise it returns null.
Syntax:
string.match(regExp);
<script>
var str="JavaProgramming";
document.writeln(str.match("Java"));
</script>
Output:
Java
The slice() method returns the selected elements in an array, as a new array object.
The slice() method selects the elements starting at the given start argument, and ends
at, but does not include, the given end argument
Where,
41
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
Start: Optional. An integer that specifies where to start the selection (The first element has
an index of 0). Use negative numbers to select from the end of an array. If omitted, it acts
like "0"
end: Optional. An integer that specifies where to end the selection. If omitted, all elements
from the start position and to the end of the array will be selected. Use negative numbers
to select from the end of an array
Code:
<script>
var str = "JavaScript";
document.writeln(str.slice(0));
document.writeln("<br>"+str.slice(4));
</script>
Output:
JavaScript
Script
Code: Write a javascript function to insert a string within a string at a particular position.
<html>
<body>
<button onclick = "myfunction()">click</button>
<script language="javascript" type="text/javascript">
function myfunction()
{
var s1 = "client scripting";
var s2 = " side";
var output = [s1.slice(0, 6), s2, s1.slice(6)].join('');
document.write(output);
}
</script>
</body>
</html>
Output:
42
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
43
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
unit 3
Form and Event Handling
Forms are one of the most common web page elements used with JavaScript.
JavaScript is commonly used with following two reasons:
⮚ To add functionality that makes forms easier for users to fill out
1
⮚ To validate or process the data that a user enters before that data is
submitted to a server-side script.
JavaScript form object represents HTML form. HTML forms are a very powerful tool for
interacting with users.
An HTML form is used to collect user input. The user input can then be sent to a server for
processing. JavaScript’s interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
3.1: Building blocks of a Form, properties and methods of form, button, text, text area,
checkbox, radio button, select element:
A form is a section of an HTML document that contains elements such as radio buttons,
text boxes and option lists. HTML form elements are also known as controls.
Elements are used as an efficient way for a user to enter information into a form.
Typical form control objects also called “widgets” includes the following:
✔ Text box for entering a line of text.
✔ Push button for selecting an action.
✔ Radio buttons for making one selection among a group of options.
✔ Check boxes for selecting or deselecting a single, independent option.
The <form> element can contain one or more of the following form elements:
● <input>
● <textarea>
● <button>
● <select>
● <option>
● <fieldset>
● <label>
● <legend>
2
Syntax:
3 <input type = “file”> “file” onchange An input held for entering the
name of a file to upload to
the web server, value
property is read only.
3
9 <select> “select-on onchange A list or drop-down menu
e” from which one item may be
selected.
1. name: Can be used so that the value of the element can be processed.
2. type: Can be used to specify the type of input.
3. id: Identification name of element.
4. value: Can be used to specify the initial value. It is required when type is set to
checkbox or radio. It should not be used when type is set to file.
5. checked: Can be used when type is set to checkbox or radio to set the initial state of a
checkbox or radio button to be selected.
6. maxlength: Can be used to specify the maximum number of characters allowed in a
textbox.
7. src: Can be used when type is set to image to specify the location of an image file.
8. alt: Can be used when type is set to image to specify the alternative text of the image,
which should be a short description.
Code: To accept first name, last name, email and birthdate. After clicking on button, details
will be displayed as an output.
<html>
<head>
<style>
fieldset
4
{
background-color: pink;
}
legend
{
background-color: gray;
color: white;
padding: 5px 10px;
}
input
{
margin: 5px;
}
</style>
</head>
<body>
<form action=" ">
<fieldset>
<legend>Personalia:</legend>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday"><br><br>
</fieldset>
</form>
<p>Click the button to get the details:</p>
<button onclick="myFunction()">Details</button>
<BR>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
5
<script>
function myFunction()
{
var y = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = y;
var x = document.getElementById("lname").value;
document.getElementById("demo1").innerHTML = x;
var z = document.getElementById("email").value;
document.getElementById("demo2").innerHTML = z;
var w = document.getElementById("birthday").value;
document.getElementById("demo3").innerHTML = w;
}
</script>
</body>
</html>
Output:
6
Properties and Methods:
• The Form object represents a <form> element in an HTML document. The elements
property is an HTML collection that provides convenient access to all elements of
the form. The submit () and reset () methods allow a form to be submitted or reset
under program control.
• Each form in a document is represented as an element of the documents.forms[]
array. The elements of a form are collected in the array like object Form.elements.
Properties of Form:
Sr. Properties Description
No.
1 action Read/Write string that reflects the action attribute of the form.
2 elements[ ] An array containing all of the elements of the form. Use it to loop
through form easily.
3 encoding Read/Write string that specifies how the form data is encoded.
4 length The number of elements in the form.
5 method Read/Write string that specifies how the method the form is
submitted.
6 name The name of the form.
7 target The name of the target frame or window form is to be submitted to.
Methods of Form:
Sr. Methods Description
No.
1 reset() Resets the form
2 submit() Submits a form
Methods of Events:
Sr. Methods Description
No.
1 onReset Code is executed when the form is reset.
2 onSubmit Code is executed when form is submitted.
7
document.forms.book.title.value="CSS_book";
document.forms.book.author.value="Manisha Padwal";
}
</script>
</head>
<body>
<form id="book">
Title of Book:<input id="title"> <br> <br>
Author of Book:<input id="author"> <br> <br>
<input type="button" id="btn" value="Assign Values" onclick="assign()">
</form>
</body>
</html>
Output:
getElementById() method :
▪ The getElementById() method returns the element that has the ID attribute with the
specified value.
▪ This method is one of the most common methods in the HTML DOM, and is used
almost every time you want to manipulate, or get info from, an element on your
document.
8
Syntax:
document.getElementById(elementID);
Code: Following code displays after clicking on button, text color is changed as red.
<html>
<body>
<script>
function myFunction()
{
var x = document.getElementById("demo");
x.style.color = "red";
}
</script>
</body>
</html>
Output:
2. getElementsByName() method
9
The getElementsByName() method returns a collection of all elements in the document
with the specified name (the value of the name attribute).
Syntax:
document.getElementsByName(name);
Code: Check all <input> elements with type="checkbox" in the document that have a name
attribute with the value "animal":
<html>
<body>
<input name="program" type="checkbox" value="IF">
Information Technology <br>
<input name="program" type="checkbox" value="CO">
Computer Engineering
<br>
<p>Click the button to check all checkboxes that have a name attribute with the value
"program".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = document.getElementsByName("program");
var i;
for (i = 0; i < x.length; i++)
{
if (x[i].type == "checkbox")
{
x[i].checked = true;
}
}
}
</script>
</body>
</html>
Output:
10
3. getElementsByTagName() method
Syntax:
document.getElementsByTagName(tagname);
Code: Following code illustrates the use of getElementsByTagName() to count how many LI
elements are present in unordered list.
Find out how many <li> elements there are in the document.
<html>
<body>
<p>An unordered list:</p>
<ul>
<li>Information Technology</li>
<li>Computer Engineering</li>
<li>Chemical Engineering</li>
</ul>
<p>Click the button to find out how many li elements there are in this document. </p>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction()
11
{
var x = document.getElementsByTagName("LI");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
Output:
Code: Change the background color of all <p> elements in the document as pink and text
color as blue.
<html>
<body>
<p>Computer Engineering</p>
<p>Information Technology</p>
12
}
</script> </body> </html>
Output:
4) getElementsByClassName() Method
The getElementsByClassName() method returns an object containing all the
elements with the specified class names in the document as objects. Each element
in the returned object can be accessed by its index. This method can be called upon
any individual element to search for its descendant elements with the specified class
names.
Syntax:
document.getElementsByClassName(classnames);
Parameters: This method takes only one parameter, which is a string containing
space-separated class names of the elements to search for.
Example:
<!DOCTYPE html>
<html>
<head>
<title>DOM getElementByClassName() Method</title>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
.example {
padding: 10px;
margin: auto;
margin-top: 10px;
border: 1px solid black;
13
width: 300px;
}
</style>
</head>
<body>
<h1>Client_side Scripting</h1>
<h2>DOM getElementByClassName() Method</h2>
<div>
<h4 class="example">div1</h4>
<h4 class="yellowBorder example">div2</h4>
<h4 class="greenBorder example">div3</h4>
<h4 class="example">div4</h4>
</div>
<script>
document.getElementsByClassName('greenBorder example')[0]
.style.border="10px solid green";
document.getElementsByClassName('yellowBorder example')[0]
.style.border="10px solid yellow";
</script>
</body>
</html>
Output:
5) innerHTML property
14
The easiest way to modify the content of an HTML element is by using
the innerHTML property.
Code: Script for count the number of <p> tag and <H2> tag.
<html>
<head>
<style>
div
{
border: 1px solid black;
margin: 5px;
}
</style>
15
</head>
<body>
<div id="myDIV">
<p>Information Technology</p>
<p>Computer Engg.</p>
<p>Electronics and Telecommunication</p>
<p>Chemical Engg.</p>
</div>
<div id="myh">
<H2>Vidyalankar Polytechnic</H2>
<H2>Vidyalankar Institute of Technology </H2>
</div>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction()
{
var x = document.getElementById("myDIV").getElementsByTagName("P");
document.getElementById("demo").innerHTML = x.length;
var y = document.getElementById("myh").getElementsByTagName("H2");
document.getElementById("demo1").innerHTML = y.length;
}
</script>
</body>
</html>
Output:
16
Code:
<script type="text/javascript">
function changeText()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('vp').innerHTML = userInput;
}
</script>
<p>Welcome <b id='vp'>JavaScript</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText()' value='Change Text'/>
Output:
Code:
<html>
<body>
Name: <input type="text" id="userInputName" value=""> <br> <br>
Password: <input type="password" id="userInputPwd" value=""> <br> <br>
<input type="button" onclick="changeText()" value="Change Text">
<p>Name is <b id="vp">JavaScript</b> </p>
17
<p>Password is <b id="vp1">JavaScript</b> </p>
<script>
function changeText()
{
var userInputName = document.getElementById("userInputName").value;
document.getElementById("vp").innerHTML = userInputName;
var userInputPwd = document.getElementById("userInputPwd").value;
document.getElementById("vp1").innerHTML = userInputPwd;
}
</script>
</body>
</html>
Output:
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
18
</body>
</html>
Output:
The innerText property can be used to write the dynamic text on the html document. Here,
text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.
In this example, we are going to display the password strength when releases the key after
press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
19
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
20
<button name = “btn” value = “MyButton” onclick = “msg()”>
Inside a <button> element you can put content, like text or images. But this is not the case
with the buttons created with <input> tag.
Attribute Value Description
name name Specifies a name for the button
type button Specifies the type of button
reset
submit
value text Specifies an initial value for the button
OR
<button onclick="Function_name()"> Click me </button>
Code:
<html>
<body>
<h2>Show a Push Button</h2>
<p>The button below activates a JavaScript when it is clicked. </p>
<form>
<input type="button" value="Click me" onclick="msg()">
</form>
<script>
function msg()
{
alert("Hello world!");
}
</script>
</body>
</html>
Output:
21
Code:
<html>
<body>
<h3>The onclick Event using Button tag. </h3>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Welcome to JavaScript";
}
</script>
</body>
</html>
Output:
Code:
<html>
<body>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").onclick = function()
{
myFunction()
};
function myFunction()
22
{
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
Output:
Input “text” is an object to enter a single line of text whose content will be part of form
data.
In html a text is created by following code:
<input type=”text” name=”textname” id=”textid” value=” assign_value” />
Code:
<script type="text/javascript">
function changeText()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('vp').innerHTML = userInput;
}
</script>
23
The Textarea object represents an HTML <textarea> element.
The <textarea> tag indicates a form field where the user can enter a large amount of text.
You can access a <textarea> element by using getElementById():
Attributes of TextArea tag:
Property Description
cols Sets or returns the value of the cols attribute of a text area
name Sets or returns the value of the name attribute of a text area
rows Sets or returns the value of the rows attribute of a text area
value Sets or returns the contents of a text area
wrap Sets or returns the value of the wrap attribute of a text area.
• Soft: “Soft" forces the words to wrap once inside the textarea but
once the form is submitted, the words will no longer appear as
such, and line breaks and spacing are not maintained.
• Hard :"Hard" wraps the words inside the text box and places line
breaks at the end of each line so that when the form is submitted
the text will transfer as it appears in the field, including line breaks
and spacing.
• "Off“: sets a textarea to ignore all wrapping and places the text into
one ongoing line.
textareaObject.wrap = soft/hard/off
readonly Setting a "yes" or "no" value for the readonly attribute determines whether
or not a viewer has permission to manipulate the text inside the text field.
disabled Disabling the textarea altogether prevents the surfer from highlighting,
copying, or modifying the field in any way. To accomplish this, set
the disabled property to "yes".
Code: to demonstrate the <textarea> and its attributes.
<html>
<body>
24
</body>
</html>
Output:
In above code, disabled="yes" that is textarea is disabled (cannot perform any highlighting,
copying, or modifying) .
Without using “disabled” attribute of <textarea>
<textarea cols="30" rows="5" wrap="hard" readonly="yes">
Output will be like:
25
</html>
Output:
Methods of TextArea:
Method Description
select() Selects the entire contents of a text area
26
<input> elements of type checkbox are rendered by default as boxes that are checked
(ticked) when activated. A checkbox allows you to select single values for submission in a
form (or not).
Syntax for creating checkbox is:
<input type="checkbox" id="myCheck" onclick="myFunction()">
A checkbox can have only two states:
1. Checked
2. Unchecked
Code:
<html>
<body>
<div>
Program:
<br>
<input type="checkbox" name="program" id="it" value="IT">
<label for="it">Information Tech</label> <br>
27
<div id="status">
</div>
<script>
function validate()
{
var elements = document.getElementsByName("program");
var statusText = " ";
for (var index=0; index <elements. Length; index++)
{
statusText = statusText + elements[index].value+"="+elements[index].checked+"<br>";
}
document.getElementById("status").innerHTML = statusText;
}
</script>
</body>
</html>
Output:
The radio button allows the user to choose one of a predefined set of options. You can
define groups with the name property of the radio buttons.
Radio buttons with the same name belong to the same group. Radio buttons with different
names belongs to the different groups. At most one radio button can be checked in a group.
Syntax:
28
<input type="radio" id="male" name="gender" value="male">
Code:
<html>
<body>
<form method="post" action=" " onsubmit="return ValidateForm();">
<fieldset>
<legend>Select Course:</legend>
<input type="radio" name="br" value="IT" checked>IT<br>
<input type="radio" name="br" value="CO">CO<br>
<input type="radio" name="br" value="EJ">EJ<br>
<br>
<input type="submit" value="Submit now">
</fieldset>
</form>
<script type="text/javascript">
function ValidateForm()
{
var obj = document.getElementsByName("br");
for(var i = 0; i < obj.length; i++)
{
if(obj[i].checked == true)
{
if(confirm("You have selected " + obj[i].value))
return true;
else
return false;
}
}
}
</script>
</body>
</html>
Output:
29
Form SELECT elements (<select>) within your form can be accessed and manipulated in
JavaScript via the corresponding Select object.
To access a SELECT element in JavaScript, use the syntax:
document.myform.selectname //where myform and selectname are names of your
form/element.
document.myform.elements[i] //where i is the position of the select element within form
Property Description
30
disabled Sets or returns whether an option is disabled, or not
Code: Disable the third option (index 2) in a drop-down list and apply color as red to
disabled index.
<html>
<body>
<select id="programs" size="5">
<option>Computer Engineering</option>
<option>Information Technology</option>
<option>Chemical Engineering</option>
<option>Electronics & TeleComm.</option>
</select>
<p>Click the button to disable the third option (index 2) in the dropdown list.</p>
<script>
function myFunction()
{
var x = document.getElementById("programs").options[2].disabled = true;
31
document.getElementById("programs").options[2].style.color = "red";
}
</script>
</body>
</html>
Output:
<html>
<body>
Select a Program and click the button:
<select id="mySelect">
<option>Information Technology</option>
<option>Computer Engg</option>
<option>Civil Engg</option>
<option>Electronics and Telecommunication</option>
</select>
<button type="button" onclick="myFunction()">
Display index</button>
<script>
function myFunction()
{
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
32
alert("Index: " + y[x].index + " is " + y[x].text);
}
</script>
</body>
</html>
Output:
3. 2 Form Events:
The form property within the document object contains an array of all forms defined within
the document.
Each element within the array is a form object, the index number associated with the form
object defines the order in which the form appears on the webpage.
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser. When
javascript code is included in HTML, javascript react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus,
javascript handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add javascript code, which will execute
the task to be performed on the event.
33
Object Event Handler
hidden none
reset onReset
submit onSubmit
The main utility of a button object is to trigger an event, say an onClick() event, but a button
object has no default action.
● submit
● reset
● button
These events are fired when some click related activity is registered.
Form events:
34
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element (The onblur
event occurs when an object loses focus.)
change onchange When the user modifies or changes the value of a form
element
Code: onfocus event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" green";
}
</script>
</body>
</html>
Output:
<p>When you submit the form, a function is triggered which alerts some text.</p>
35
<input type="submit" value="Submit">
</form>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Output:
<p>When you leave the input field, a function is triggered which transforms the input
text to upper case.</p>
<script>
function myFunction()
{
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
document.getElementById("fname").style.color="blue";
}
</script>
</body>
</html>
Output:
36
Window/Document events:
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
37
Code: onresize event
<html>
<body onresize="myFunction()">
<p>Try to resize the browser window to display the windows height and width.</p>
<p id="demo"></p>
<script>
function myFunction()
{
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Output:
38
Code: onclick event
d
Output:
Mouse Events:
Attribute Value Description
onclick script Fires on a mouse click on the element
ondblclick script Fires on a mouse double-click on the element
onmousedown script Fires when a mouse button is pressed down on an
element
onmousemove script Fires when the mouse pointer is moving while it is over an
element
onmouseout script Fires when the mouse pointer moves out of an element
onmouseover script Fires when the mouse pointer moves over an element
onmouseup script Fires when a mouse button is released over an element
onwheel script Fires when the mouse wheel rolls up or down over an
element
oncontextmenu script oncontextmenu event occurs when the user right-clicks
on an element to open the context menu.
39
<html>
<body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="1"
src="aa.jpg" width="64" height="64">
<script>
function bigImg(x)
{
x.style.height ="120px";
x.style.width ="120px";
}
function normalImg(x)
{
x.style.height = "64px";
x.style.width = "64px";
}
</script>
</body>
</html>
Output:
40
<script>
function myFunction()
{
document.getElementById("aa").style.fontSize = "35px";
}
</script>
</body>
</html>
Output:
<script>
function color_change()
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
}
</script>
</body>
</html>
Output:
41
Code: onmousedown and onmouseup event
<html>
<body>
42
<html>
<head>
<style>
div {
background: yellow;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div oncontextmenu="myFunction()" contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
</div>
<script>
function myFunction()
{
alert("You right-clicked inside the div!");
}
</script>
</body>
</html>
Output:
43
Execute a JavaScript when moving the mouse pointer over a <div> element and display the
x and y coordinates.
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<p>This example demonstrates how to assign an "onmousemove" event to a div
element.</p>
<div onmousemove="myFunction(event)"></div>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
<script>
function myFunction(e)
{
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
document.getElementById("demo").innerHTML = coor;
}
</script>
</body>
</html>
Output:
44
<!DOCTYPE HTML>
<html>
<head>
<title>Example: Working with Mouse events</title>
<style>
body{font-family:Verdana;
background:#44c767; color:#fff;}
</style>
<script>
var count = 0;
function tracker(){
count++;
alert(count + " Mouse moves have been registered");
}
function popup1() {
alert("Event Registered : onMouseOver");
}
function popup2() {
alert("Event Registered : onMouseOut");
}
45
</script>
</head>
<body>
<p>Move the mouse over the link to trigger the event
<a href="#" onmouseover="popup1()"> onMouseOver</a></p>
______________-
<!DOCTYPE HTML>
<html>
<head><title>Javascript Events: Attach an Event Listener</title>
</head>
<body>
<p id="content">We must let go of the life we have planned,
so as to accept the one that is waiting for us </p>
</body>
<script>
var p = document.getElementById("content");
http://www.tutorialspark.com/javascript/JavaScript_Mouse_Event.php
KeyEvent:
Event Description
1) The onkeydown event occurs when the user is pressing a key (on the keyboard).
The keydown event occurs when the user presses down a key on the keyboard. 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.
47
k
Output:
2) The onkeyup event occurs when the user releases a key (on the keyboard).
Syntax: <element onkeyup="myScript">
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.
Code: onkeyup event
<html>
<body>
<input type="text" onkeyup="alert('You have released a key inside text input!')">
<hr>
<textarea cols="30" onkeyup="alert('You have released a key inside
textarea!')"></textarea>
<p><strong>Note:</strong> Try to enter some text inside input box and textarea.</p>
</body>
</html>
Output:
3) The onkeypress event occurs when the user presses a key (on the keyboard).
48
Syntax: <element onkeypress="myScript">
The keypress event occurs when a user presses down a key on the keyboard that has a
character value associated with it. For example, keys like Ctrl, Shift, Alt, Esc, Arrow keys,
etc. will not generate a keypress event, but will generate a keydown and keyup event.
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.
Code: onkeypress event
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
<script>
function myFunction()
{ document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
</html>
Output:
49
<p>Press a key inside the text field to set a red background color.</p>
function myFunction()
{
document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Mouse Events</title>
<style>
#target-div {
width: 320px;
height: 150px;
background: blue;
margin-bottom: 10px;
}
</style>
<script>
50
function clickHandler(evt) {
var html = "evt.altKey=" + evt.altKey;
document.getElementById("log-div").innerHTML = html;
}
</script>
</head>
<body>
<h3>Press Ctrl key and Click</h3>
<div id="target-div" onclick="clickHandler(event)" >
</div>
<div style="color:red;" id="log-div">
</div>
</body>
</html>
3.3 Changing an attribute value dynamically:
The change in any attribute value can be reflected to the user by highlighting the value or
text by some color.
The onchange event is associated with many elements <input>, <select> of a form object
and helpful to make call to a function where the change of attribute value code is written.
In following example onchange event is used with two textboxes and whenever user will
make chage in value of these textboxes, text color and background of text boxes will
change.
Code: onchange event to change text color as blue and background color is pink.
<html>
<head>
<script type="text/javascript">
function highlight(x)
{
x.style.color="blue";
x.style.backgroundColor="pink";
}
</script>
51
</head>
<body>
<form name="myform" action=" " method="post">
Institute Name:
<input type="text" name="iname" onchange="highlight(this)"/>
<BR>
Program:
<input type="text" name="infotech" onchange="highlight(this)"/>
<br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Output:
<script>
function myFunction(val)
{
alert("The input value has changed. The new value is: " + val);
}
</script>
</body>
</html>
Output:
52
“with” keyword
The with keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of
the block that follows. The properties and methods for the object can be used without
naming the object.
Syntax:
with (object)
{
Properties used without the object name and dot
}
Example:
53
Output: Output:
Code: Following example provides two radio buttons to the user one is for fruits and
another is for vegetables.
When user will select the fruits radio button, the option list should present only the fruits
names to user and when user will select the vegetable radio button, the option list should
present only the vegetable names to user so that user can select an appropriate element of
interest.
<html>
<body>
<html>
<script type="text/javascript">
function modifyList(x)
{
with(document.forms.myform)
{
if(x ==1)
{
optionList[0].text="Kiwi";
optionList[0].value=1;
optionList[1].text="Pine-Apple ";
optionList[1].value=2;
optionList[2].text="Apple";
optionList[2].value=3;
}
if(x ==2)
{
54
optionList[0].text="Tomato";
optionList[0].value=1;
optionList[1].text="Onion ";
optionList[1].value=2;
optionList[2].text="Cabbage ";
optionList[2].value=3;
}
}
}
</script>
</head>
<body>
<form name="myform" action=" " method="post">
<select name="optionList" size="3">
<option value=1>Kiwi
<option value=1>Pine-Apple
<option value=1>Apple
</select>
<br>
<input type="radio" name="grp1" value=1 checked="true" onclick="modifyList(this.value)">
Fruits
Code: Following example provides four list elements as name of branches. When you
select a branch from list, selected branch will be displayed as output.
<html>
<body>
55
<p>Select Program from list:</p>
<select id="mySelect" onchange="myFunction()">
<option value="CO">Computer Engg</option>
<option value="IF">Information Technology</option>
<option value="EJ">Electronics and Tele</option>
<option value="CE">Chemical Engg</option>
</select>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Output:
56
var items=document.getElementsByName('check_print');
var selectedItems="";
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"<br>";
}
document.getElementById("y").innerHTML =selectedItems;
}
</script>
</head>
<body>
<big>Select your favourite accessories: </big><br>
<input type="checkbox" name="check_print" value="red">red<br>
<input type="checkbox" name="check_print" value="Blue">Blue<br>
<input type="checkbox" name="check_print" value="Green">Green<br>
<input type="checkbox" name="check_print" value="Yellow">Yellow<br>
<input type="checkbox" name="check_print" value="Orange">Orange<br>
<p><input type="button" onclick='printChecked()' value="Click me"/></p>
You Selected:
<p id="y"></p>
</body>
</html>
Output:
57
Approach:
● Create a label element and assign an id to that element.
● Define a button that is used to call a function. It acts as a switch to change the text in
the label element.
● Define a javaScript function, that will update the label text.
● Use the innerHTML property to change the text inside the label.
The innerHTML property sets or returns the HTML content of an element.
Code: Given an HTML document and the task is to change the text and color of a label using
JavaScript.
<html>
<head>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
Client-SideScripting
</h1>
<h4>
Click on the button to change the text of a label
</h4>
<label id = "aaa">
Welcome to Client-Side Scripting Course.
</label>
<br>
<button onclick="change_L()">
Click Here!
</button>
<script>
function change_L()
{
document.getElementById('aaa').innerHTML
= "CSS is a client-side scripting language.";
document.getElementById('aaa').style.color
= "red";
}
</script>
</body>
</html>
58
Output:
59
{
var x = document.getElementById("it").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:
Code: Following example we have used one <img> tag to simulate the functionality of
submit button. Before writing the code make sure one “submit.jpg” picture should save in
your folder.
<html>
<body>
<h1>The input src attribute</h1>
60
<input type="image" src="submit.jpg" alt="Submit" width="130" height="48"
onclick="myFunction()">
</form>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("name").value;
document.write("You Submitted:<h2>" +x +"</h2>");
}
</script>
</body>
</html>
Output:
Disabling Elements:
It is common to display a form with some elements disabled, which prevents the user from
entering information into the element.
Code: Following example shows to enable and disable text field.
<html>
<body>
Name: <input type="text" id="myText">
<p>Click the button to enable/disable the text field.</p>
<button onclick="myFunction()">
change status
</button>
<script>
function myFunction()
{
var txt=document.getElementById("myText")
if ('disabled' in txt)
61
{
txt.disabled=!txt.disabled;
}
}
</script>
</body>
</html>
Output:
OR
<html>
<body>
<script>
function disableTxt()
{
document.getElementById("myText").disabled = true;
}
function undisableTxt()
{
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
Output:
62
Read only elements:
The readOnly property sets or returns whether a text field is read-only, or not.
A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy
the text from it.
Set a text field to read-only:
document.getElementById("myText").readOnly = true;
Syntax:
To return the readOnly property: textObject.readOnly
To Set the readOnly property: textObject.readOnly = true|false
<p><strong>Tip:</strong> To see the effect, try to type something in the text field before
and after clicking the button.</p>
<script>
function myFunction()
{
document.getElementById("myText").readOnly = true;
}
</script>
</body>
</html>
63
Output:
64
Unit 4
Cookies and Browser Data
4.1 Cookies- Basics of Cookies, reading a cookie value, writing a cookie value, creating Cookies,
deleting a cookie, Setting the expiration Date of Cookies
4.2 Browser-Opening a window, scrolling new window focus, window position, changing the
content of window, closing a window, scrolling a web page, multiple windows at once, creating
a web page in a new window, javascript in URLs, javascript security, Timers, Browser location
and history.
1
4.1 Cookies:
4.1.1 Basics of Cookies
A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons. It maintains the state of a user and remembers the user's information
among all the web pages.
The communication between a web browser and server happens using a stateless protocol
named HTTP. Stateless protocol treats each request independent. So, the server does not keep
the data after sending it to the browser. But in many situations, the data will be required again.
Here come cookies into a picture. With cookies, the web browser will not have to communicate
with the server each time the data is required. Instead, it can be fetched directly from the
computer.
Types of cookies
All cookies are not created equal. There are 3 types of them:
● Session: They expire when you close your browser (or if you stay inactive for a certain
time). They’re used for example on e-commerce websites so you can continue browsing
without losing what you put in your cart.
● Permanent: They persist even when the browser is closed. They have an expiration date
though and by law, you can’t make them last more than 6 months. They’re used to
remember your passwords and login info so you don’t have to re-enter them every
time.
● Third-party: Cookies attributes usually corresponds to the website domain they are on.
Not for third-party cookies—as you probably gathered from the name, they are installed
by … third-party websites (no wayy), such as advertisers. They gather data about your
browsing habits, and allow them to track you across multiple websites. Other websites
using third-party cookies: Facebook, Flickr, Google Analytics, Google Maps, Google Plus,
SoundCloud, Tumblr, Twitter and YouTube.
o When a user sends a request to the server, then each of that request is treated as a new
request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the
server browser at the client-side.
2
o Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.
You can access the cookie like this which will return all the cookies saved for the current domain.
var x = document.cookie;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
<html>
<head>
<script>
function writeCookie()
{
with(document.myform)
{
document.cookie="Name=" + person.value + ";"
alert("Cookie written");
}
3
}
function readCookie()
{
var x;
if(document.cookie=="")
x="";
else
x=document.cookie;
document.write(x);
}
</script>
</head>
<body>
<form name="myform" action="">
Enter your name:
<input type="text" name="person"><br>
<input type="Reset" value="Set Cookie" type="button" onclick="writeCookie()">
<input type="Reset" value="Get Cookie" type="button" onclick="readCookie()">
</form>
</body>
</html>
Output:
4
4.1.4 Creating a cookie
In JavaScript, we can create, read, update and delete a cookie by
using document.cookie property.
With a path parameter, you can tell the browser what path the cookie belongs to.
You don't have to specify a cookie value when you delete a cookie.
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
5
{
document.cookie="username=Vidyalanakr Polytechnic; expires=Mon, 3 Aug 2020
00:00:00 GMT";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Output:
6
For example,
document.cookie="username=VP; expires=Tues,04 Aug 2020 00:00:00 GMT ";
Code:
<html>
<head>
<script>
function writeCookie()
{
var d=new Date();
d.setTime(d.getTime()+(1000*60*60*24));
with(document.myform)
{
document.cookie="Name=" + person.value + ";expires=" +d.toGMTString();
}
}
function readCookie()
{
if(document.cookie=="")
document.write("cookies not found");
else
document.write(document.cookie);
}
</script>
</head>
<body>
<form name="myform" action="">
Enter your name:
<input type="text" name="person"><br>
<input type="Reset" value="Set C" type="button" onclick="writeCookie()">
<input type="Reset" value="Get C" type="button" onclick="readCookie()">
</form>
</body>
</html>
Output:
7
Click on “Get Cookie”
Code:
<html>
<head>
<script>
document.cookie="username=VP; expires=Tues,04 Aug 2020 00:00:00 GMT ";
if(document.cookie)
{
document.write("created cookie is:" +document.cookie);
cstr=document.cookie
var list=cstr.split("=");
document.write("<br> Split List:" +list);
if(list[0]=="username")
{
var data=list[1].split(",");
document.write("<br> Data:" +data);
var data=list[2].split(",");
document.write("<br> Data:" +data);
var data=list[3].split(",");
document.write("<br> Data:" +data);
}
8
}
</script>
</body>
</html>
Output:
4.2 Browser
A web browser (commonly referred to as a browser) is a software application for retrieving,
presenting and traversing information resources on the World Wide Web. An information
resource is identified by a Uniform Resource Identifier/ Locator (URI/URL) and may be a web
page, image, video or other piece of content. Hyperlinks present in resources enable users easily
to navigate their browsers to related resources.
Although browsers are primarily intended to use the World Wide Web, they can also be used to
access information provided by web servers in private networks or files in file systems.
The major web browsers are Firefox, Internet Explorer, Google Chrome, Opera, and Safari.
Browser's Components:
The browser's main components are:
1. The user interface:
This includes the address bar, back/forward button, bookmarking menu, etc. Every part of the
browser displays except the window where you see the requested page.
2. The browser engine: marshals’ actions between the UI and the rendering engine.
3. The rendering engine:
responsible for displaying requested content. For example, if the requested content is HTML, the
rendering engine parses HTML and CSS, and displays the parsed content on the screen.
4. Networking:
For network calls such as HTTP requests, using different implementations for different platform
behind a platform-independent interface.
5. UI backend:
9
Used for drawing basic widgets like combo boxes and windows. This backend exposes a generic
interface that is not platform specific. Underneath it uses operating system user interface
methods.
6. JavaScript interpreter.
Used to parse and execute JavaScript code.
7. Data storage.
This is a persistence layer. The browser may need to save all sorts of data locally, such as
cookies. Browsers also support storage mechanisms such as localStorage, IndexedDB, WebSQL
and Filesystem.
It is important to note that browsers such as Chrome run multiple instances of the rendering
engine: one for each tab. Each tab runs in a separate process.
Document object Model (DOM)
The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
As mentioned earlier, it is the object of window.
So
window.document
is same as
document
10
Source: https://www.javatpoint.com/document-object-model
The Document Object Model is a programming API for documents. The object model itself
closely resembles the structure of the documents it models. For instance, consider this table,
taken from an HTML document:
11
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
Method Description
12
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name
<div class="example">
Another div element with class="example"
</div>
<p>Click the button to find out how many elements with class "example" there are in this
document.</p>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementsByClassName("example");
document.getElementById("demo").innerHTML = x.length;
13
}
</script>
</body>
</html>
Output:
<div class="example">
Another div with class="example"
</div>
14
<p class="example">This is a p element with class="example".</p>
<p>Click the button to change the background color of all elements with class="example".</p>
<script>
function myFunction()
{
var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++)
{
x[i].style.backgroundColor = "red";
}
}
</script>
</body>
</html>
Output:
15
Accessing field value by document object
In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Code: Let's see the simple example of document object that prints name with welcome
message.
<script type="text/javascript">
function printvalue()
{
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Output:
16
Javascript - innerText
The innerText property can be used to write the dynamic text on the html document. Here, text
will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.
Code: In this example, we are going to display the password strength when releases the key
after press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Output:
Application of DOM:
1) To render a document such as HTML page, most web browsers use an internal model similar
to DOM. The nodes of every document are organized in a tree structure, called DOM tree, with
topmost node named as “Document Object”. When HTML page is rendered in browser, the
17
browser downloads the HTML page into local memory and automatically parses it to display the
page on screen.
2) When a web page is loaded, the browser creates a Document Object Model of the page,
which is an object-oriented representation of an HTML document, that’s act as an interface
between javascript and document itself and allows the creation of dynamic web pages.
Window object
● Window object is a top-level object in Client-Side JavaScript.
● Window object represents the browser's window.
● It represents an open window in a browser.
● It supports all browsers.
The document object is a property of the window object. So, typing window.document.write is
same as document.write.
● All global variables are properties and functions are methods of the window object.
Window Object Properties
Property Description
Document It returns the document object for the window (DOM).
Frames It returns an array of all the frames including iframes in the current window.
Closed It returns the Boolean value indicating whether a window has been closed or not.
History It returns the history object for the window.
innerHeight It sets or returns the inner height of a window's content area.
innerWidth It sets or returns the inner width of a window's content area.
Length It returns the number of frames in a window.
Location It returns the location object for the window.
Name It sets or returns the name of a window.
Navigator It returns the navigator object for the window.
Opener It returns a reference to the window that created the window.
outerHeight It sets or returns the outer height of a window, including toolbars/scrollbars.
outerWidth It sets or returns the outer width of a window, including toolbars/scrollbars.
Parent It returns the parent window of the current window.
Screen It returns the screen object for the window.
screenX It returns the X coordinate of the window relative to the screen.
screenY It returns the Y coordinate of the window relative to the screen.
Self It returns the current window.
18
Status It sets the text in the status bar of a window.
Top It returns the topmost browser window that contains frames.
Method Description
alert() It displays an alert box.
confirm() It displays a dialog box.
prompt() It displays a dialog box that prompts the visitor for input.
setInterval() It calls a function or evaluates an expression at specified intervals.
setTimeout() It evaluates an expression after a specified number of milliseconds.
clearInterval() It clears a timer specified by setInterval().
clearTimeOut() It clears a timer specified by setTimeout().
close() It closes the current window.
open() It opens a new browser window.
createPopup() It creates a pop-up window.
focus() It sets focus to the current window.
blur() It removes focus from the current window.
moveBy() It moves a window relative to its current position.
moveTo() It moves a window to the specified position.
resizeBy() It resizes the window by the specified pixels.
resizeTo() It resizes the window to the specified width and height.
print() It prints the content of the current window.
scrollBy() It scrolls the content by the specified number of pixels.
scrollTo() It scrolls the content to the specified coordinates.
Stop() Stops the window from loading.
The open() method opens a new browser window, or a new tab, depending on your
browser settings and the parameter values.
19
To open the window, javascript provides open() method.
Syntax: window.open();
window.open(URL, name, specs, replace)
<html>
<body>
<script>
document.write("Hello Everyone!!!!");
</script>
</body>
</html>
//save as sample.html
<html>
<body>
20
<script>
var ob=window.open("hello.html","windowName","top=200,left=100,width=250,height=100,status");
</script>
</body>
</html>
Output:
Code: Open a new window and close that window on button click event using open( ) and close
( ).
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>Hello Everyone.Welcome to new window.</p>");
}
function closeWin()
{
myWindow.close();
}
</script>
</body>
</html>
Output:
21
After clicking on “open myWindow” button, new window will be open.
Click on “Close myWindow” button, newly open window will be closed.
Window position:
A new window always displayed on the screen at the location which is specified by user and
location is specified by setting the left and top properties of new window as shown below:
window.open("http://vpt.edu.in", "windowName", top=500,left=500,width=400,height=400");
22
Syntax:
window.innerWidth
window.innerHeight
The outerWidth property returns the outer width of the browser window, including all interface
elements (like toolbars/scrollbars).
The outerHeight property returns the outer height of the browser window, including all interface
elements (like toolbars/scrollbars).
Syntax:
window.outerWidth
window.outerHeight
Output:
23
Window.screen:
Properties:
Proprties Description
screen. availTop Returns the top side of the area on the screen that is available for
application windows.
screen.availLeft Returns the left side of the area on the screen that is available for
application windows.
screen.availWidth returns the width of the visitor's screen, in pixels, minus interface features
like the Windows Taskbar.
screen.availHeight returns the height of the visitor's screen, in pixels, minus interface features
like the Windows Taskbar.
screen.left Retrieves the horizontal offset of top-left corner of the current screen
relative to the top-left corner of the main screen in pixels.
screen.top Retrieves the vertical offset of top-left corner of the current screen relative
to the top-left corner of the main screen in pixels.
24
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<p id="demo5"></p>
<p id="demo6"></p>
<p id="demo7"></p>
<script>
document.getElementById("demo").innerHTML =
"Available screen height is " + screen.availHeight;
document.getElementById("demo1").innerHTML =
"Available screen width is " + screen.availWidth;
document.getElementById("demo2").innerHTML =
"Available screen avilable Top is " + screen.availTop;
document.getElementById("demo3").innerHTML =
"Available screen avilable Left is " + screen.availLeft;
document.getElementById("demo4").innerHTML =
"Available screen Top is " + screen.top;
document.getElementById("demo5").innerHTML =
"Available screen Left is " + screen.left;
document.getElementById("demo6").innerHTML =
"Available screen Width is " + screen.width;
document.getElementById("demo7").innerHTML =
"Available screen Height is " + screen.height;
</script>
</body>
</html>
Output:
25
Window provides two methods which also deal with positioning of windows named scrollBy()
and moveTo() method.
scrollBy(): The scrollBy() method scrolls the document by the specified number of pixels.
Syntax: window.scrollBy(xnum, ynum)
Code: Scroll the document by 100px vertically:
<html>
<head>
<style>
body
{
width: 5000px;
}
button
{
position: fixed;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window by 100px horizontally.</p>
<p>Look at the horizontal scrollbar to see the effect.</p>
<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>
26
<script>
function scrollWin()
{
window.scrollBy(100, 0);
}
</script>
</body>
</html>
Output:
The moveTo() method moves a window's left and top edge to the specified coordinates.
Syntax: window.moveTo(x, y)
The focus() method is used to give focus to an element (if it can be focused).
Syntax: HTMLElementObject.focus()
Code: simple example of moveTo ( )
<html>
<body>
<button onclick="openWin()">Create new window</button>
<button onclick="moveWinTo()">Move new window</button>
<button onclick="moveWinBy()">
Move the new window by 75 * 50px
</button>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "", "width=250, height=250");
}
function moveWinTo()
27
{
myWindow.moveTo(150, 150);
myWindow.focus();
}
function moveWinBy()
{
myWindow.moveBy(75, 50);
myWindow.focus();
}
</script>
</body>
</html>
Output:
28
<body>
<script>
function openWin1(ad)
{
myWindow = window.open(ad, "myWindow", "width=500,height=500");
}
</script>
<button value="Google" onclick="openWin1('https://www.google.com')">Google</button>
<button value="Vidyalankar" onclick="openWin1('http://vpt.edu.in')">Vidyalanakr</button>
</body>
</html>
29
Scrolling a Web Page
Syntax: window.scrollTo(xpos,ypos);
Where,
Xpos: Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
Ypos: Required. The coordinate to scroll to, along the y-axis (vertical), in pixels
Code: to scroll the document window to 100 pixels horizontally and vertically.
<html>
<head>
<style>
body
{
width: 5000px;
height: 5000px;
}
</style>
</head>
<body>
<script>
30
function scrollHorizontal()
{
window.scrollTo(100, 0);
}
function scrollVertical()
{
window.scrollTo(0,100);
}
</script>
<p>Click the button to scroll the document window to 100 pixels horizontally and vertically.</p>
</body>
</html>
Output:
When user clicks on “Click me to scroll horizontally!” the output will be like this:
31
When user clicks on “Click me to scroll vertically!” the output will be like this:
Creation of multiple window is possible by creating and opening window in a loop using
window.open( ) method.
The only thing needs to take care is to pass proper dimension for window so that newly created
window will not appear one upon another.
Code: In following example, x variable is assigned to top dimension of window and y variable is
assigned to left dimension of window.
<html>
<head>
<title>window </title>
<script type="text/javascript">
function show( )
32
{
for(i=0; i< 250 ; i=i+50)
{
var x=i+50;
var y=i+50;
winobj=window.open('','win' +i, 'top='+x+ ',left='+y+',width=300, height=200');
}
}
</script>
</head>
<body>
<input type="multiple" value="Show Multiple Windows" type="button" onclick="show()"/>
</body>
</html>
Output:
You can place dynamic content into a new window by using the document.write( ) method.
All html tags can be written inside document.write( ) method.
33
Code:
<html>
<head>
<title>window </title>
<script type="text/javascript">
function newWindow()
{
winobj=window.open("","winname","width=300, height=300, left=200, top=200");
winobj.document.write('<html>');
winobj.document.write('<head>');
winobj.document.write('<title> writing Content</title>');
winobj.document.write('</head>');
winobj.document.write('<body>');
winobj.document.write('<form action="" method="post">');
winobj.document.write('<p>');
winobj.document.write('Enter Inst Name:<input type="text" name="iname">');
winobj.document.write('<br>');
winobj.document.write('<input type="submit" name="submit">');
winobj.document.write('</p>');
winobj.document.write('</form>');
winobj.document.write('</body>');
winobj.document.write('</html>');
winobj.focus();
}
</script>
</head>
<body>
<input type="button" value="New value" onclick="newWindow()">
</body>
</html>
Output:
34
Stop()
This method may be useful if the loading of an image or frame takes too long.
Syntax: window.stop();
<html>
<head>
<script>window.stop();</script>
</head>
<body>
<p>The stop() method stops this text and the iframe from loading.</p>
<p><b>Note:</b> This method does not work in Internet Explorer.</p>
<iframe src="https://vpt.edu.in/"></iframe>
</body>
35
</html>
Javascript in URL
Another way that JavaScript code can be included on the client side is in a URL following the
javascript: pseudo-protocol specifier. This special protocol type specifies that the body of the
URL is arbitrary JavaScript code to be interpreted by the JavaScript interpreter. If the JavaScript
code in a javascript: URL contains multiple statements, the statements must be separated from
one another by semicolons. Such a URL might look like the following:
When the browser "loads" one of these JavaScript URLs, it executes the JavaScript code
contained in the URL and displays the "document" referred to by the URL. This "document" is the
string value of the last JavaScript statement in the URL. This string will be formatted and
displayed just like any other document loaded into the browser. More commonly, a JavaScript
URL will contain JavaScript statements that perform actions but return no value.
For example:
javascript:alert("Hello World!");
When this sort of URL is "loaded," the browser executes the JavaScript code, but, because there
is no value to display as the new document, it does not modify the currently displayed
document.
Javascript security
https://snyk.io/learn/javascript-security/
https://blog.jscrambler.com/the-most-effective-way-to-protect-client-side-javascript-applicat
ions
Timers
36
● 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.
The setTimeout() Method
window.setTimeout(function, milliseconds);
Code: Click a button. Wait 3 seconds, and the page will alert "Hello":
<html>
<body>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction()
{
alert('Hello');
}
</script>
</body>
</html>
Output:
37
The clearTimeout() method stops the execution of the function specified in setTimeout().
window.clearTimeout(timeoutVariable)
The window.clearTimeout() method can be written without the window prefix.
The clearTimeout() method uses the variable returned from setTimeout():
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
If the function has not already been executed, you can stop the execution by calling
the clearTimeout() method:
Code:
<html>
<body>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>
<script>
function myFunction()
{
alert("Hello");
}
</script>
</body>
</html>
Output:
38
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
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).
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
Output:
39
How to Stop the Execution?
The clearInterval() method stops the executions of the function specified in the setInterval() method.
window.clearInterval(timerVariable)
Output:
40
Code: Rotating images using setTimeout(0 method. Following example is using an array of
images. Using setTimeout(0 method images will be rotated after 1 second.
<html>
<body>
<script>
var i,imgs,pic;
function init()
{
pic=document.getElementById("pic");
imgs=["red.png","blue.png","green.png","yellow.png"];
i=0;
rotate();
}
function rotate()
{
pic.src=imgs[i];
(i==(imgs.length-1))?i=0:i++;
setTimeout(rotate,1000);
}
document.addEventListener("DOMContentLoaded",init,false);
</script>
</head>
<body>
<img id="pic" width="300" height="300">
</body>
</html>
Output:
41
Code: Moving car using setTimeout( ) and clearTimeout( ) methods.
<html>
<head>
<title>Animation </title>
<script type="text/javascript">
var obj=null;
var animate;
function init()
{
obj=document.getElementById('car');
obj.style.position='relative';
obj.style.left='0px';
}
function start()
{
obj.style.left=parseInt(obj.style.left)+ 10 + 'px';
animate=setTimeout(start,20);
}
function stop()
{
clearTimeout(animate);
obj.style.left='0 px';
}
window.onload=init;
42
</script>
</head>
<body>
<img id="car" src="car.jpg">
<br><br>
<input value="Start" type="button" onclick="start()"/>
<input value="Stop" type="button" onclick="stop()"/>
</body>
</html>
Output:
Code: Writing a number after a delay using setInterval ( ) method. In this example, numbers are
displayed in a textarea after a 1 second.
<html>
<head>
43
<title>number </title>
<script type="text/javascript">
var number=0;
var timerId=null;
function magic()
{
if(timerId==null)
{
timerId=setInterval("display()",1000);
}
}
function display()
{
if(number > 15)
{
clearInterval(timerId);
return;
}
document.getElementById("output").innerHTML+=number;
number++;
}
</script>
</head>
<body>
<button onclick="magic();">
Click me
</button>
<br>
Output:
44
Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.
1. window.navigator
Or,
1. navigator
45
Navigator Object Properties
Method Description
Code:
<html>
<body>
<script type="text/javascript">
document.write("<b>Browser: </b>"+navigator.appName+"<br><br>");
46
document.write("<b>Browser Version: </b>"+navigator.appVersion+"<br><br>");
document.write("<b>Browser Code: </b>"+navigator.appCodeName+"<br><br>");
document.write("<b>Platform: </b>"+navigator.platform+"<br><br>");
document.write("<b>Cookie Enabled: </b>"+navigator.cookieEnabled+"<br><br>");
document.write("<b>User Agent: </b>"+navigator.userAgent+"<br><br>");
document.write("<b>Java Enabled: </b>"+navigator.javaEnabled()+"<br><br>");
</script>
</body>
</html>
Output:
Location Object
● Location object is a part of the window object.
● It is accessed through the 'window.location' property.
● It contains the information about the current URL.
Property Description
hash It returns the anchor portion of a URL.
47
port It returns the port number the server uses for a URL.
Method Description
assign() It loads a new document.
reload() It reloads the current document.
Code:
<script type="text/javascript">
//note some parts may be blank depending on your URL
alert("hash: " + location.hash + "\n" +
"host: " + location.host + "\n" +
"hostname: " + location.hostname + "\n" +
"href: " + location.href + "\n" +
"pathname: " + location.pathname + "\n" +
"port: " + location.port + "\n" +
"protocol: " + location.protocol + "\n" +
"search: " + location.search );
</script>
Output:
48
History Object
● History object is a part of the window object.
● It is accessed through the window.history property.
● It contains the information of the URLs visited by the user within a browser window.
History Object Properties
Property Description
Length It returns the number of URLs in the history list.
Next It returns the URL of the next document in the History object.
Previous It returns the URL of the last document in the history object.
Method Description
back() It loads the previous URL in the history list.
49
<html>
<head>
<title>GeeksforGeeks back() example</title>
</head>
<body>
<b>Press the back button</b>
<input type="button" value="Back" onclick="previousPage()">
<script>
function previousPage() {
window.history.back();
}
</script>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<style>
#myProgress
{
width: 100%;
height: 30px;
position: relative;
background-color: #ddd;
}
#myBar
{
background-color: #4CAF50;
width: 5px;
height: 30px;
position: absolute;
}
50
</style>
<body>
<div id="myProgress">
<div id="myBar">
</div>
</div>
<br>
<button onclick="move()">Click Me</button>
<script>
function move()
{
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame,200);
function frame()
{
if (width == 100)
{
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
</script>
</body>
</html>
51
Toggle between two background
<!DOCTYPE html>
<html>
<body>
<script>
var myVar = setInterval(setColor, 300);
function setColor() {
var x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myVar);
}
</script>
</body>
</html>
<script>
// program to stop the setInterval() method after five times
let count = 0;
// function creation
let interval = setInterval(function(){
52
let dateTime= new Date();
let time = dateTime.toLocaleTimeString();
document.write("<br>"+time);
}, 2000);
</script>
53
Unit 5
Regular Expression, Rollover and Frames
Marks: 14 (R-2, U-6, A-6)
Course Outcome: Create interactive web pages using regular expressions for validations.
Unit Outcome:
1) Compose relevant regular expression for the given character pattern search.
2) Develop JavaScript to implement validations using the given regular expression.
3) Create frame based on the given problem.
4) Create window object a per the given problem.
5) Develop JavaScript for creating rollover effect for the given situation.
The JavaScript RegExp class represents regular expressions, and both String and RegExp
define methods that use regular expressions to perform powerful pattern-matching and
search-and-replace functions on text.
A regular expression is very similar to a mathematical expression, except a regular
expression tells the browser how to manipulate text rather than numbers by using special
symbols as operators.
Syntax:
A regular expression is defined with the RegExp () constructor as:
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Here,
● Pattern – A string that specifies the pattern of the regular expression or another
regular expression.
● Attributes – An optional string containing attributes that specify global,
case-insensitive, and multi-line matches.
Brackets
Brackets ([ ]) have a special meaning when used in the context of regular expressions.
The [abc] expression is used to find any character between the brackets.
The characters inside the brackets can be any characters or span of characters:
Code: Do a global search for the characters "i" and "s" in a string:
<html>
<body>
<p>Click the button to do a global search for the characters "i" and "s" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "Do you know if this is all there is?";
var patt1 = /[is]/gi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
5.1.2 Finding non-matching Characters
The [^abc] expression is used to find any character NOT between the brackets.
The characters inside the brackets can be any characters or span of characters:
Example:
<html> <script>
function check()
{
var exp=/[^\*]/;
var res=exp.test(document.getElementById("txt1").value);
document.getElementById("demo1").innerHTML=res;
}
</script>
<body>
Enter text:<textarea id="txt1"></textarea>
<input type="button" onclick="check()" value="Ckeck">
<p id="demo1"></p>
</body>
</html>
Output:
Code: Do a global search for characters that are NOT "i" and "s" in a string:
<html>
<body>
<p>Click the button to do a global search for characters that are NOT "i" and "s" in a
string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Do you know if this is all there is?";
var patt1 = /[^is]/gi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
The [^0-9] expression is used to find any character that is NOT a digit.
The digits inside the brackets can be any numbers or span of numbers from 0 to 9.
Syntax
new RegExp("[^0-9]")
or simply:
/[^0-9]/
Syntax with modifiers
new RegExp("[^0-9]", "g")
or simply:
/\[^0-9]/g
Code: Do a global search for numbers that are NOT "1" and “s” in a string.
<html>
<body>
<p>Click the button to do a global search for numbers that are NOT "1" and "s"in a
string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "12121212This is JavaScript";
var patt1 = /[^1s]/gi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Code: Do a global search for the number "1" and “s” in a string:
<html>
<body>
<p>Click the button to do a global search for the number "1" and “s” in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "12121212This is Javascript";
var patt1 = /[1s]/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.
Code: The n+ quantifier matches any string that contains at least one n.
<html>
<body>
<p>Click the button to do a global search for at least one "o" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "Hellooo World! Hello Vidyalanakr School!";
var patt1 = /o+/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Code: The n* quantifier matches any string that contains zero or more occurrences of n.
<html>
<body>
<p>Click the button to do a global search for at least one "o" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hellooo World! Hello Vidyalanakr School!";
var patt1 = /o+/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Code: The n? quantifier matches any string that contains zero or one occurrences of n.
<html>
<body>
<p>Click the button to do a global search for a "1", followed by zero or one "0"
characters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "1, 100 or 1000?";
var patt1 = /10?/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Code:The n{X,Y} quantifier matches any string that contains a sequence of X to Y n's.
X and Y must be a number.
<html>
<body>
<p>Click the button to global search for a substring that contains a sequence of three to
four digits.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "100, 1000 or 10000?";
var patt1 = /\d{3,4}/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script> </body> </html>
Output:
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to
give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style Regular
Expressions.
Sr.No. Character & Description
. (dot)
1
a single character
\s
2
a whitespace character (space, tab, newline)
\S
3
non-whitespace character
\d
4
a digit (0-9)
\D
5
a non-digit
\w
6
a word character (a-z, A-Z, 0-9, _)
\W
7
a non-word character
[\b]
8
a literal backspace (special case).
9 [aeiou]
matches a single character in the given set
[^aeiou]
10
matches a single character outside the given set
(foo|bar|baz)
11
matches any of the alternatives specified
● You can have the browser check to see whether the text has digits or non-digits by
writing a regular expression. The regular expression must contain either \d or \D,
depending on whether you want the browser to search the text for digits (\d) or
nondigits (\D).
● The \d symbol, tells the browser to determine whether the text contains digits.
The browser returns a true if at least one digit appears in the text.
● You'd use this regular expression to determine whether a first name has any digits,
The \D symbol is used to tell the browser to search for any nondigit in the text.
● The browser returns a true if a nondigit is found. This is the regular expression you
would use to validate a telephone number, assuming the userwas asked to enter
digits only. If the browser finds a nondigit, the telephone number is invalid and you
can notify the user who entered the information into the form.
Output:
Output:
Code: The \D metacharacter is used to find a non-digit character.
<html> <body>
<p id="demo">Click the button to do a global search for non-digit characters in a
string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Give 100%!";
var patt1 = /\D/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script> </body> </html>
Output:
Code: The . metacharacter is used to find a single character, except newline or other line
terminators.
<html>
<body>
<p>Click the button to do a global search for "h.t" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "That's hot!";
var patt1 = /h.t/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
5.1.5 Matching Punctuation and Symbols
● You can have the browser determine whether text contains or doesn't contain
letters, punctuation, or symbols, such as the @ sign in an e-mail address, by using
the \w and \W special symbols in a regular expression.
● The \w special symbol tells the browser to determine whether the text contains a
letter, number, or an underscore, and the \W special symbol reverses this request
by telling the browser to determine whether the text contains a character other
than a letter, number, or underscore.
● You can use the following regular expression to determine whether the product
name that was entered into the form on your web page contains a symbol:
/\W/
● Using \W is equivalent to using [a-zA-Z0-9].
Example:
<html>
<script>
function check()
{
var exp=/\w{2}/;
var str=document.getElementById("txt").value;
var res=exp.test(str);
document.getElementById("demo1").innerHTML=res;
}
</script>
<body>
Enter text:<textarea id="txt"></textarea>
<input type="button" onclick="check()" value="check">
<p id="demo1"></p>
</body>
</html>
Output:
Code: The \w metacharacter is used to find a word character.
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.
<html>
<body>
<p>Click the button to do a global search for word characters in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "Give 100%!";
var patt1 = /\w/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
● You might want the browser to search for a particular word within the text. A word
is defined by a word boundary—that is, the space between two words. You define
a word boundary within a regular expression by using the \b special symbol.
● You need to use two \b special symbols in a regular expression if you want the
browser to search for a word: the first \b represents the space at the beginning of
the word and the second represents the space at the end of the word.
Example:
<html>
<script>
function check()
{
var exp=/\b\w{2}\b/;
var str=document.getElementById("txt").value;
var res=exp.test(str);
document.getElementById("demo1").innerHTML=res;
}
</script>
<body>
Enter text:<textarea id="txt"></textarea>
<input type="button" onclick="check()" value="check">
<p id="demo1"></p>
</body>
</html>
Output:
<html> <body>
<p>Click the button to return the position where the tab character was found in a string.
</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "Visit Vidyalankar Polytechnic.\t To Learn JavaScript.";
var patt1 = /\t/;
var result = str.search(patt1);
document.getElementById("demo").innerHTML = result;
}
</script> </body>
</html>
Output:
Modifiers/flag
Several modifiers are available that can simplify the way you work with regexps, like case
sensitivity, searching in multiple lines, etc.
Sr.No. Modifier & Description
i
1
Perform case-insensitive matching.
m
2 Specifies that if the string has newline or carriage return characters, the ^ and $
operators will now match against a newline boundary, instead of a string
boundary
g
3
Performs a global match that is, find all matches rather than stopping after the first
match.
Code: The g modifier is used to perform a global match (find all matches rather than
stopping after the first match).
Syntax:
new RegExp("regexp", "g")
or simply:
/regexp/g
Example: 1)
<html>
<body>
<p>Click the button to do a global search for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Example 2):
<html>
<body>
<p>Click the button to do a global search for the character-span [a-h] in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /[a-h]/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
Code:
The i modifier is used to perform case-insensitive matching.
Syntax
new RegExp("regexp", "i")
or simply:
/regexp/i
Example:
<html>
<body>
<p>Click the button to do a global, case-insensitive search for "is" in a string.
</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Is this all there is?";
var patt1 = /is/gi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
The m modifier treat beginning (^) and end ($) characters to match the beginning or end of
each line of a string (delimited by \n or \r), rather than just the beginning or end of the
string.
Syntax:
new RegExp("regexp", "m")
or simply:
/regexp/m
Example:
<html>
<body>
<p>Click the button to do a global, case-insensitive, multiline search for "is" at the
beginning of each line in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "\nIs th\nis h\nis?";
var patt1 = /^is/gmi;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Output:
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
Sr.No. Method & Description
exec()
1
Executes a search for a match in its string parameter.
test()
2
Tests for a match in its string parameter.
toSource()
3
Returns an object literal representing the specified object; you can use this value
to create a new object.
toString()
4
Returns a string representing the specified object.
The replace() method searches a string for a specified value, or a regular exp
Syntax
string.replace(searchvalue, newvalue)
Example:
<html>
<script>
function check()
{
var exp=/:/g;
var str=document.getElementById("txt").value;
var res=str.replace(exp,"-");
document.getElementById("demo1").innerHTML=res;
}
</script>
<body>
Enter text:<textarea id="txt"></textarea>
<input type="button" onclick="check()" value="check">
<p id="demo1"></p>
</body>
</html>
Output:
Code:
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/blue/g, "red");
document.getElementById("demo").innerHTML = res;
document.getElementById("demo").style.color = "red";
}
</script>
</body>
</html>
Output:
The exec method searches string for text that matches regexp. If it finds a match, it
returns an array of results; otherwise, it returns null.
Syntax
RegExpObject.exec( string );
Code:
<html>
<head>
<title>JavaScript RegExp exec Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.exec(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.exec(str);
document.write("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>
Output:
The test method searches string for text that matches regexp. If it finds a match, it returns
true; otherwise, it returns false.
Syntax
RegExpObject.test( string );
Code:
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
Output:
The search() method searches a string for a specified value, and returns the position of the
match.
Code:
<html>
<body>
Output:
Here is a list of the properties associated with RegExp and their description.
Sr.No. Property & Description
constructor
1
Specifies the function that creates an object's prototype.
2 global
Specifies if the "g" modifier is set.
ignoreCase
3
Specifies if the "i" modifier is set.
lastIndex
4
The index at which to start the next match.
multiline
5
Specifies if the "m" modifier is set.
source
6
The text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of
RegExp properties.
ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a
particular regular expression performs case-insensitive matching, i.e., whether it was
created with the "i" attribute.
Syntax:
RegExpObject.ignoreCase
Code:
<html>
<head>
<title>JavaScript RegExp ignoreCase Property</title>
</head>
<body>
<script type = "text/javascript">
var re = new RegExp( "string" );
if ( re.ignoreCase )
{
document.write("Test1-ignoreCase property is set");
} else
{
document.write("Test1-ignoreCase property is not set");
}
if ( re.ignoreCase )
{
document.write("<br/>Test2-ignoreCase property is set");
} else
{
document.write("<br/>Test2-ignoreCase property is not set");
}
</script>
</body>
</html>
Output:
if ( re.multiline )
{
document.write("<br/>Test2-multiline property is set");
}
Else
{
document.write("<br/>Test2-multiline property is not set");
}
</script>
</body>
</html>
Output:
5.2 Frames
HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document. A collection of frames in the browser
window is known as a frameset. The window is divided into frames in a similar way the
tables are organized: into rows and columns.
cols
Specifies how many columns are contained in the frameset and the size of each
column. You can specify the width of each column in one of the four ways −
Absolute values in pixels.
For example, to create three vertical frames, use cols = "100, 500, 100".
1
A percentage of the browser window. For example, to create three vertical frames,
use cols = "10%, 80%, 10%".
Using a wildcard symbol.
For example, to create three vertical frames, use cols = "10%, *, 10%". In this case
wildcard takes remainder of the window.
2 rows
This attribute works just like the cols attribute and takes the same values, but it is
used to specify the rows in the frameset. For example, to create two horizontal
frames, use rows = "10%, 90%". You can specify the height of each row in the same
way as explained above for columns.
border
3
This attribute specifies the width of the border of each frame in pixels. For example,
border = "5". A value of zero means no border.
frameborder
4 This attribute specifies whether a three-dimensional border should be displayed
between frames. This attribute takes value either 1 (yes) or 0 (no). For example,
frameborder = "0" specifies no border.
framespacing
This attribute specifies the amount of space between frames in a frameset. This can
5 take any integer value.
For example:
framespacing = "10" means there should be 10 pixels spacing between each frame.
1
src
This attribute is used to give the file name that should be loaded in the frame. Its
value can be any URL. For example, src = "/html/top_frame.htm" will load an HTML
file available in html directory.
name
2 This attribute allows you to give a name to a frame. It is used to indicate which
frame a document should be loaded into. This is especially important when you
want to create links in one frame that load pages into an another frame, in which
case the second frame needs a name to identify itself as the target of the link.
frameborder
3 This attribute specifies whether or not the borders of that frame are shown; it
overrides the value given in the frameborder attribute on the <frameset> tag if one is
given, and this can take values either 1 (yes) or 0 (no).
marginwidth
4 This attribute allows you to specify the width of the space between the left and right
of the frame's borders and the frame's content. The value is given in pixels. For
example, marginwidth = "10".
marginheight
5 This attribute allows you to specify the height of the space between the top and
bottom of the frame's borders and its contents. The value is given in pixels. For
example, marginheight = "10".
noresize
6
By default, you can resize any frame by clicking and dragging on the borders of a
frame. The noresize attribute prevents a user from being able to resize the frame.
scrolling
7 This attribute controls the appearance of the scrollbars that appear on the frame.
This takes values either "yes", "no" or "auto". For example, scrolling = "no" means it
should not have scroll bars.
Example:
<html>
<head>
<title>Create a Frame</title>
</head>
<frameset rows="30%,20%,*" frameborder="1" border="20" bordercolor="blue"
scrolling="auto" noresize>
<frame src="webpage1.html" name="topPage" />
<frame src="webpage2.html" name="bottomPage" />
<frameset cols="30%,*">
<frame src="webpage3.html" name="bottomPage" />
<frameset rows="50%,*" frameborder="0" bordercolor="red">
<frame src="webpage3.html" name="bottomPage" />
<frame src="webpage3.html" name="bottomPage" />
</frameset>
</frameset></frameset>
</html>
Output:
5.2.2 Invisible border of Frame
User can hide border by using frameborder attribute.
frameborder
This attribute specifies whether or not the borders of that frame are shown; it overrides
the value given in the frameborder attribute on the <frameset> tag if one is given, and this
can take values either 1 (yes) or 0 (no).
Example:
<html>
<head>
<title>Create a Frame</title>
</head>
<frameset rows="30%,20%,*" frameborder="0">
<frame src="webpage1.html" name="topPage" />
<frame src="webpage2.html" name="bottomPage" />
<frameset cols="30%,*">
<frame src="webpage3.html" name="bottomPage" />
<frameset rows="50%,*" frameborder="0" bordercolor="red">
<frame src="webpage3.html" name="bottomPage" />
<frame src="webpage3.html" name="bottomPage" />
</frameset>
</frameset></frameset>
</html>
Output:
Sample.html
<html>
<head>
<title>Frame</title>
</head>
<frameset rows="50%,50%">
<frame src="webpage1.html" name="topPage" frameborder="0" border="0" />
<frame src="webpage2.html" name="bottomPage" frameborder="0" border="0" />
</frameset>
</html>
Webpage1.html
<html>
<head>
<title>web page1</title>
<script>
function ChangeContent()
{
parent.topPage.location.href="webpage3.html";
}
</script>
</head>
<body>
<input name="webpage1" value="WebPage1" type="button" /><br>
</body>
</html>
Webpage2.html
<html>
<head>
<title></title>
</head>
<body>
<input name="WebPage2" value="Web Page2" type="button" />
</body>
</html>
Webpage3.html
<html>
<input name="WebPage3" value="web Page3" type="button" />
</html>
You can access and change the value of elements of another child window by directly
referencing the element from within your JavaScript. You must explicitly
specify the full path to the element in the JavaScript statement that references the
element, and it must be from the same domain as the web page; otherwise, a security
violation occurs.
<html>
<head>
<title>Create a Frame</title>
<script >
function ChangeContent()
{
window.topPage.document.open()
window.topPage.document.writeln('<html >')
window.topPage.document.writeln('<head>')
window.topPage.document.writeln('<title>Web Page 3</title>')
window.topPage.document.writeln('</head>')
window.topPage.document.writeln('<body>')
window.topPage.document.writeln(
'<FORM name="Form1" action="" method="post">')
window.topPage.document.writeln('<P>')
window.topPage.document.writeln('<input name="Text1" type="text"/>
window.topPage.document.writeln(
'<INPUT name="WebPage1" value="Web Page 1" type="button" />')
window.topPage.document.writeln('</P>')
window.topPage.document.writeln('</FORM>')
window.topPage.document.writeln('</body>')
window.topPage.document.writeln('</html>')
window.topPage.document.close()
}
</script>
</head>
<frameset rows="50%,50%" onload="ChangeContent()">
<frame src="webpage1.html" name="topPage" />
<frame src="webpage2.html" name="bottomPage" />
</frameset>
</html>
<html>
<head>
<title></title>
</head>
<script>
function accessElement()
{
parent.topPage.Form1.Text1.value="Manisha";
parent.topPage.Form1.WebPage1.value="Accessed";
}
</script>
<body>
<h1>Web Page 2</h1>
<input name="WebPage2" value="Web Page2" type="button" onclick="accessElement()" />
</body>
</html>
Note: This Frameset and javascript is not supported by browser.
IFRAMES
You can define an inline frame with HTML tag <iframe>. The <iframe> tag is not somehow
related to <frameset> tag, instead, it can appear anywhere in your document. The <iframe>
tag defines a rectangular region within the document in which the browser can display a
separate document, including scrollbars and borders. An inline frame is used to embed
another document within the current HTML document.
The src attribute is used to specify the URL of the document that occupies the inline
frame.
Example:
<html>
<body>
<h3>A demonstration of how to access an IFRAME element</h3>
<iframe id="myFrame" src="webpage2.html"></iframe>
<iframe id="myFrame1" src="webpage1.html"></iframe>
<p>Click the button to get the URL of the iframe.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction()
{
var x = document.getElementById("myFrame").src;
document.getElementById("demo").innerHTML = x;
var y = document.getElementById("myFrame1").src;
document.getElementById("demo1").innerHTML = y;
}
</script>
</body>
</html>
Output:
Key Difference: Frame is a HTML tag that is used to divide the web page into various
frames/windows. Used as <frame> tag, it specifies each frame within a frameset tag.
Iframe as <iframe> is also a tag used in HTML but it specifies an inline frame which means it
is used to embed some other document within the current HTML document.
iframe_p.html
The window.postMessage() method safely enables cross-origin communication
between Window objects; e.g., between a page and a pop-up that it produced, or
between a page and an iframe embedded within it.
<html>
<head>
<script>
function send()
{
window.parent.postMessage('Hello Parent Frame!', '*');
}
</script>
</head>
<title> IFrame Test </title>
<body>
<h1> Welcome </h1>
<p> Hello There </body>
<button onclick="send()">Send</button>
</body>
</html>
Output:
5.3 Rollover
Rollover means a webpage changes when the user moves his or her mouse over an object
on the page. It is often used in advertising. There are two ways to create rollover, using
plain HTML or using a mixture of JavaScript and HTML. We will demonstrate the creation
of rollovers using both methods.
The keyword that is used to create rollover is the <onmousover> event.
For example, we want to create a rollover text that appears in a text area. The text “What
is rollover?” appears when the user place his or her mouse over the text area and the
rollover text changes to “Rollover means a webpage changes when the user moves his
or her mouse over an object on the page” when the user moves his or her mouse away
from the text area.
The HTML script is shown in the following example:
<html>
<head></head>
<Body>
<textarea rows=”2″ cols=”50″ name=”rollovertext” onmouseover=”this.value=’What is
rollover?'”
onmouseout=”this.value=’Rollover means a webpage changes when the user moves his or
her mouse over an object on the page'”></textarea>
</body>
</html>
In following example, we create a rollover effect that can change the color of its text using
the style attribute.
<p
onmouseover=”this.style.color=’red'”
onmouseout=”this.style.color=’blue'”>
Move the mouse over this text to change its color to red. Move the mouse away to
change the text color to blue.
</p>
<p>When the target attribute of a link matches the name of an iframe, the link will open in
the iframe.</p>
</body>
</html>
Output:
<html> <head>
<title>
text rollovers</title>
<script>
function update_details()
{
document.getElementById("i1").src="blue.png";
document.getElementById("detail").innerHTML="<h3> Blue Color </h3> <br> shape:Circle
<br> file type:png";
}
</script>
</head>
<body>
<table id="t1" border="1" width="100%">
<tbody>
<tr valign="top">
<td width="50%">
<a><img id="i1" height="500" src="green.png" width="900" name="clr"
onmouseover="update_details()"></a></td>
<td id="detail">
<h3> Green Color </h3>
<br> shape:Rectangle
<br> file type:png
</td>
</tr>
</tbody>
</table>
</body>
</html>
Output:
When user moves mouse over an image, description and image will chage.
if(clrname==3)
{
document.clr.src="blue.png";
mwin=window.open('','myadwin','height=100,width=150,left=500,top=200');
mwin.document.write("looks like blue color");
}
}
</script>
</head>
<body>
<table border="1" width="100%">
<tbody>
<tr valign="top">
<td width="50%">
<a><img height="500" src="red.png" width="900" name="clr"></a></td>
<td><H2>
<a onmouseover="open_new_window(1)" onmouseout="mwin.close()">
<b><u>RED</u></b></a>
<br><br>
<a onmouseover="open_new_window(2)" onmouseout="mwin.close()">
<b><u>GREEN</u></b></a>
<br><br>
<a onmouseover="open_new_window(3)" onmouseout="mwin.close()">
<b><u>BLUE</u></b></a>
</H2>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Output:
5.3.4 More efficient Rollover
We can avoid the delay by loading all images once when they are referred first time on
web page.
Code:
<html>
<head>
<title>
text rollovers</title>
<script>
b=new Image;
r=new Image;
g=new Image;
if(document.images)
{
b.src='blue.png';
r.src='red.png';
g.src='green.png';
}
else
{
b.src='';
r.src='';
g.src='';
document.clr='';
}
</script>
</head>
<body>
<table border="1" width="100%">
<tbody>
<tr valign="top">
<td width="50%">
<a><img height="500" src="blue.png" width="900" name="clr"></a></td>
<td><H2>
<a onmouseover="document.clr.src='blue.png'">
<b><u>BLUE</u></b></a>
<br><br>
<a onmouseover="document.clr.src='red.png'">
<b><u>RED</u></b></a>
<br><br>
<a onmouseover="document.clr.src='green.png'">
<b><u>GREEN</u></b></a>
</H2>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Output:
<html>
<head>
</head>
<body>
<script>
function valid_email(str)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(str))
else
valid_email('[email protected]');
</script>
</body>
</html>
Unit 6
Unit Outcome:
1) Develop Javascript to manage the given status bar.
2) Develop javascript to create the given banner.
3) Develop javascript to create the given slideshow.
4) Develop javascript to create the given menu.
5) Develop javascript to protect a webpage in a specified manner.
6.1 Status bar-builds a static message, changing the message using rollover, moving the
message using rollover
6.2 Banner-loading and displaying banner advertisement. Linking a banner advisement to
url
6.3 Slide show – creating a slideshow
6.4 Menus-creating a pulldown menu, dynamically changing a menu, validating a menu
selection, Floating menu, chain select menu, Tab menu, Pop-up menu, sliding menu,
Highlighted menu, Folding a tree menu, context menu, scrollable menu, side bar menu
6.5 Protective web page-Hiding your code, disabling the right mouse button, javascript,
concealing e-mail address
6.6 Frameworks of javascript and it]\s application.
6.1. Status Bar
The status property of the Window interface was originally intended to set the text in the
status bar at the bottom of the browser window. However, the HTML standard now
requires setting window.status to have no effect on the text displayed in the status bar.
Syntax:
window.status = string;
var value = window.status;
<html>
<head>
<title>JavaScript Status Bar</title></head>
<body>
<a href="http://www.vpt.edu.in"
onMouseOver="window.status='Vidyalankar';return true"
onMouseOut="window.status='';return true">
Vidyalankar
</a>
</body>
</html>
Output:
6.2 Banner
The banner advertisement is the hallmark of every commercial web page. It is typically
positioned near the top of the web page, and its purpose is to get the visitor's attention by
doing all sorts of clever things.
Nearly all banner advertisements are in a file format such as a GIF, JPG, TIFF, or other
common graphic file format. Some are animated GIFs, which is a series of images
contained in one file that rotate automatically on the screen. Some are Flash movies that
require the visitor to have a browser that includes a Flash plug-in. Many banner
advertisements consist of a single graphical image that does not contain any animation
and does not require any special plug-in.
You need to do three things to incorporate a banner advertisement in your web page:
1. Create several banner advertisements using a graphics tool such as Photoshop. You'll
want to make more than one advertisement so you can rotate them on your web page
using a JavaScript.
2. Create an <img> element in your web page with the height and width necessary to
display the banner advertisement.
3. Build a JavaScript that loads and displays the banner advertisements in conjunction with
the <img> element.
You load the banner advertisements into an array by declaring an Array() object and
initializing it with the file name of each banner advertisement. For example, suppose you
have three banner advertisements that are contained in the 1.jpg, 2.jpg, and 3.jpg files.
Here's how you'd load them into an Array() object:
<html >
<head>
<title>Banner Ads</title>
<script>
Banners = new Array('1.jpg','2.jpg','3.jpg');
CurrentBanner = 0;
function DisplayBanners()
{
if (document.images);
{
CurrentBanner++;
if (CurrentBanner == Banners.length)
{
CurrentBanner = 0;
}
document.RotateBanner.src= Banners[CurrentBanner];
setTimeout("DisplayBanners()",1000);
}
}
</script>
</head>
<body onload="DisplayBanners()" >
<center>
<img src="1.jpg" width="400"
height="75" name="RotateBanner" />
</center>
</body>
</html>
6.3 Slideshow:
A slideshow is similar in concept to a banner advertisement in that a slideshow rotates
multiple images on the web page. However, unlike a banner advertisement, a slideshow
gives the visitor the ability to change the image that's displayed: the visitor can click the
Forward button to see the next image and the Back button.
Creating a slideshow:
<html>
<title>slideshow</title>
<body>
<h2 class="w3-center">Manual Slideshow</h2>
<div class="w3">
<img class="mySlides" src="y.jpg" style="width:50%">
<img class="mySlides" src="yy.jpg" style="width:50%">
<img class="mySlides" src="yyy.jpg" style="width:50%">
<img class="mySlides" src="yyyy.jpg" style="width:50%">
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n)
{
showDivs(slideIndex += n);
}
function showDivs(n)
{
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length)
{
slideIndex = 1
}
if (n < 1)
{
slideIndex = x.length
}
for (i = 0; i < x.length; i++)
{
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</body>
</html>
Automatic Slideshow:
<html>
<head>
<title>Automatic Slideshow</title>
</head>
<body>
<h2 class="aa">Automatic Slideshow</h2>
<div class="aa" style="max-width:500px">
<img class="mySlides" src="y.jpg" style="width:200%">
<img class="mySlides" src="yy.jpg" style="width:200%">
<img class="mySlides" src="yyy.jpg" style="width:200%">
<img class="mySlides" src="yyyy.jpg" style="width:200%">
</div>
<script>
var myIndex = 0;
auto_slide_show();
function auto_slide_show()
{
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(auto_slide_show, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>
6.4 Menus:
A menu consists of a set of options which are presented to the user. Menus are common in
graphical user interface such as Windows or Mac OS.
The Menu component provides the pull-down menu element that's common in most
graphical user interfaces (GUIs). Using a familiar GUI element will reduce the interface
learning curve of your web site or application for new users, as well as help all users more
easily find what they're looking for. Having menus that contain links to sections at various
levels in your web site can improve both the navigation of the site and the real estate of
your web pages.
6.4.1 Creating pull-down menu:
Code: Create a simple menu: If user not selected any menu, alert should be displayed.
Select Fruit:
<select id="ddlFruits">
<option value=""></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Orange</option>
</select>
<input type="submit" value="Validate" onclick="return Validate()" />
<script type="text/javascript">
function Validate()
{
var ddlFruits = document.getElementById("ddlFruits");
if (ddlFruits.value == "") {
//If the "Please Select" option is selected display error.
alert("Please select an option!");
return false;
}
return true;
}
</script>
Code: Design a drop-down menu for various colours. After selecting any colour from
menu, background colour should be changed.
1) demo2.html
2) demo2-script.js
3) demo2-style.css
HTML file:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo 2</title>
<link rel="stylesheet" href="demo2-style.css">
</head>
<body>
<div class="container">
<label for="color">Choose a Background Color:</label>
<select name="color" id="color" class="color" onchange="changeColor()">
<option value="white">White</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
</select>
</div>
<script type="text/javascript" src="demo2-script.js"></script>
</body>
</html>
JavaScript file:
changeColor = () => {
var color = document.getElementById("color").value;
switch(color){
case "white":
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
document.getElementById("color").style.backgroundColor = "white";
document.getElementById("color").style.color = "black";
break;
case "black":
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
document.getElementById("color").style.backgroundColor = "black";
document.getElementById("color").style.color = "white";
break;
case "blue":
document.body.style.backgroundColor = "blue";
document.body.style.color = "white";
document.getElementById("color").style.backgroundColor = "blue";
document.getElementById("color").style.color = "white";
break;
case "red":
document.body.style.backgroundColor = "red";
document.body.style.color = "white";
document.getElementById("color").style.backgroundColor = "red";
document.getElementById("color").style.color = "white";
break;
case "yellow":
document.body.style.backgroundColor = "yellow";
document.body.style.color = "black";
document.getElementById("color").style.backgroundColor = "yellow";
document.getElementById("color").style.color = "black";
break;
default:
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
document.getElementById("color").style.backgroundColor = "white";
document.getElementById("color").style.color = "black";
break;
}
}
CSS file:
*{
box-sizing: border-box;
}
body {
font-family: "Calibri", "Roboto", sans-serif;
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
body::-webkit-scrollbar {
display: none;
}
.container{
margin: 10%;
text-align: center;
}
.color{
width: 30%;
outline: none;
height: 30px;
background: transparent;
}
Code: Following example provides two radio buttons to the user one is for fruits and
another is for vegetables.
When user will select the fruits radio button, the option list should present only the fruits
names to user and when user will select the vegetable radio button, the option list should
present only the vegetable names to user so that user can select an appropriate element
of interest.
<html>
<body>
<html>
<script type="text/javascript">
function modifyList(x)
{
with(document.forms.myform)
{
if(x ==1)
{
optionList[0].text="Kiwi";
optionList[0].value=1;
optionList[1].text="Pine-Apple ";
optionList[1].value=2;
optionList[2].text="Apple";
optionList[2].value=3;
}
if(x ==2)
{
optionList[0].text="Tomato";
optionList[0].value=1;
optionList[1].text="Onion ";
optionList[1].value=2;
optionList[2].text="Cabbage ";
optionList[2].value=3;
}
}
}
</script>
</head>
</body>
<form name="myform" action=" " method="post">
<select name="optionList" size="3">
<option value=1>Kiwi
<option value=1>Pine-Apple
<option value=1>Apple
</select>
<br>
<input type="radio" name="grp1" value=1 checked="true"
onclick="modifyList(this.value)"> Fruits
Code: Following example provides four list elements as name of branches. When you
select a branch from list, selected branch will be displayed as output.
<html>
<body>
<p>Select Program from list:</p>
<select id="mySelect" onchange="myFunction()">
<option value="CO">Computer Engg</option>
<option value="IF">Information Technology</option>
<option value="EJ">Electronics and Tele</option>
<option value="CE">Chemical Engg</option>
</select>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Output:
Code:
<html>
<script language="Javascript">
function validate()
{
if(document.form.city.selectedIndex=="")
{
alert ( "Please select city!");
return false;
}
var sel = document.getElementById("city");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
alert("You have selected : "+selectedText);
return true;
}
</script>
<form name="form" method="post" onSubmit="return validate()"><pre>
Select your City <select name="city" id="city">
<option value="Select">Select</option>
<option value="Delhi">Delhi</option>
<option value="Jaipur">Jaipur</option>
<option value="Agra">Agra</option>
<option value="Bangalore">Bangalore</option>
<option value="Pune">Pune</option>
</select>
<input type="submit" name="Submit" value="Submit">
</pre></form>
</html>
Output:
6.4.4. Floating Menu
Also known as "fixed menus" and "hovering menus", floating menus stay in a fixed position
when you scroll the page. They appear to "float" on top of the page as you scroll.
Code:
<html>
<title>Example</title>
<style>
body {
background-image: url('/pix/samples/bg1.gif');
}
main {
margin-bottom: 200%;
}
.floating-menu {
font-family: sans-serif;
background: yellowgreen;
padding: 5px;;
width: 130px;
z-index: 100;
position: fixed;
}
.floating-menu a,
.floating-menu h3 {
font-size: 0.9em;
display: block;
margin: 0 0.5em;
color: white;
}
</style>
<main>
<p>Scroll down and watch the menu remain fixed in the same position, as though it was
floating.</p>
<nav class="floating-menu">
<h3>Floating Menu</h3>
<a href="c_sub.txt">C</a>
<a href="C++_sub.txt">C++</a>
<a href="java_sub.txt">Java</a>
<a href="python_sub.txt">Python</a>
</nav>
</main>
Output: scroll down the page to observe the output:
<html>
<head><title>chained menu</title></head>
<script>
var stateObject = {
"Maharashtra": {
"Mumbai": ["Wadala", "Nerul"],
"Pune": ["Aundh","Kothrud"]
},
"Karnataka": {
"Banglore": ["Mysoor", "Ooty"],
}
}
window.onload = function ()
{
var aaa = document.getElementById("aaa"),
bbb = document.getElementById("bbb"),
ccc = document.getElementById("ccc");
for (var state in stateObject)
{
aaa.options[aaa.options.length] = new Option(state, state);
}
aaa.onchange = function ()
{
bbb.length = 1; // remove all options bar first
ccc.length = 1; // remove all options bar first
if (this.selectedIndex < 1) {
bbb.options[0].text = "Please select city first"
ccc.options[0].text = "Please select area first"
return; // done
}
bbb.options[0].text = "Please select city"
for (var citi_name in stateObject[this.value]) {
bbb.options[bbb.options.length] = new Option(citi_name, citi_name);
}
if (bbb.options.length==2)
{
bbb.selectedIndex=1;
bbb.onchange();
}
}
aaa.onchange(); // reset in case page is reloaded
bbb.onchange = function ()
{
ccc.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
{
ccc.options[0].text = "Please select area first"
return; // done
}
ccc.options[0].text = "Please select area first"
var cities = stateObject[aaa.value][this.value];
for (var i = 0; i < cities.length; i++) {
ccc.options[ccc.options.length] = new Option(cities[i], cities[i]);
}
if (ccc.options.length==2)
{
ccc.selectedIndex=1;
ccc.onchange();
}
}
}
</script>
</body>
<form name="myform" id="myForm">
<select name="optone" id="aaa" size="1">
<option value="" selected="selected">Select state</option>
</select>
<br>
<br>
<select name="opttwo" id="bbb" size="1">
<option value="" selected="selected">Please select city first</option>
</select>
<br>
<br>
<select name="optthree" id="ccc" size="1">
<option value="" selected="selected">Please select area first</option>
</select>
</form>
</body>
</html>
Output:
6.4.6 Tab Menu
Using tab menu, more complete description is displayed below the tab bar as the visitor
clicks the mouse cursor over the tabs.
2-ways to create tab menu:
a) Using button
b) Using target selector
Code: In following example, created 3 buttons using <button>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'Mumbai')">Mumbai</button>
<button class="tablinks" onclick="openCity(event, 'Bhopal')">Bhopal</button>
<button class="tablinks" onclick="openCity(event, 'Panaji')">Panaji</button>
</div>
Code: Following example shows how to create tab menu by using target selector<a>.
<html>
<head>
<style>
:target
{
color:white;
border: 2px solid #F4D444;
background-color:green;
}
</style>
</head>
<body>
<p><a href="#news1">Mumbai is capital of Maharashtra.</a></p>
<p><a href="#news2">Bhopal is capital of Madhyapradesh.</a></p>
<p>Click on the links above and the :target selector highlight the current active HTML
anchor.</p>
<h3>
<p id="news1"><b>Mumbai</b></p>
<p id="news2"><b>Bhopal</b></p>
</h3>
</body>
</html>
Output:
Code:
<html>
<head>
<style>
.tab div {
display: none;
}
.tab div:target {
display: block;
}
</style>
</head>
<body>
<div class="tab">
<a href="#link1">Link 1</a>
<a href="#link2">Link 2</a>
<a href="#link3">Link 3</a>
<div id="link1">
<h3>Content to Link 1</h3>
<p>Hello World!</p>
</div>
<div id="link2">
<h3>Content to Link 2</h3>
<h4>Great success!</h4>
</div>
<div id="link3">
<h3>Content to Link 3</h3>
<p>Yeah!</p>
</div>
</div>
</body>
</html>
Output:
6.4.7. Popup Menu:
A popup menu appears as the user moves the mouse cursor over a parent menu item. The
popup menu contains child menu items that are associated with the parent menu item.
Code:
<html>
<head>
<style>
.dropbtn {
background-color: Blue;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: red;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
<html>
<head>
<style>
#menu
{
position: fixed;
right: -8.5em;
top: 20%;
width: 8em;
background: pink;
color: red;
margin: -1;
padding: 0.5em 0.5em 0.5em 2.5em;
}
#menu:hover
{
right: 0
}
#menu
{
transition: 0.2s
}
#menu a
{
position: relative;
left: 0;
}
#menu a:focus
{
left: -7em;
}
#menu a { transition: 0.1s }
#menu:hover a:focus {
left: 0;
background: none;
}
</style>
</head>
<body>
<h3>
<ul id=menu>
<li><a href="#home">Home</a>
<li><a href="#prog">Programs</a>
<li><a href="#vision">Vision</a>
<li><a href="#mission">Mission</a>
</ul>
</div>
</body>
</html>
6.4.9. Highlighted Menu:
User can highlight menu by using following methods:
1) When user performs onmouseover()
2) When user performs onclick()
Code:
<html>
<head>
<title>Highlighted Menu Effect</title>
<style>
.link
{
text-decoration: none;
padding: 10px 16px;
background-color:pink;
font-size: 20px;
}
.active, .link:hover
{
background-color:gray;
color:white;
}
</style>
</head>
<body>
Move the mouse over menus:<br><br>
<div id="me">
<a href="#file" class="link">File</a>
<a href="#edit" class="link">Edit</a>
<a href="#view" class="link">View</a>
<a href="#exit" class="link">Exit</a>
</div>
</body>
</html>
Output:
<html>
<head>
<style>
ul, #myUL {
list-style-type: none;
}
#myUL {
margin: 0;
padding: 0;
}
.caret {
cursor: pointer;
-webkit-user-select: none; /* Safari 3.1+ */
-moz-user-select: none; /* Firefox 2+ */
-ms-user-select: none; /* IE 10+ */
user-select: none;
}
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
.caret-down::before {
-ms-transform: rotate(90deg); /* IE 9 */
-webkit-transform: rotate(90deg); /* Safari */'
transform: rotate(90deg);
}
.nested {
display: none;
}
.active {
display: block;
}
</style>
</head>
<body>
<ul id="myUL">
<li><span class="caret">India</span>
<ul class="nested">
<li>Karnataka</li>
<li>Tamilnaadu</li>
<li><span class="caret">Maharashtra</span>
<ul class="nested">
<li>Mumbai</li>
<li>Pune</li>
<li><span class="caret">Navi Mumbai</span>
<ul class="nested">
<li>Nerul</li>
<li>Vashi</li>
<li>Panvel</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
</script>
</body>
</html>
Output:
6.4.11. Context Menu:
The context menu appears on the web page when the user clicks the right button on the
screen.
Code:
<html>
<head>
<style>
div {
background: yellow;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
</div>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.scrollmenu {
background-color: #333;
overflow: auto;
white-space: nowrap;
}
div.scrollmenu a {
display: inline-block;
color: white;
text-align: center;
padding: 14px;
text-decoration: none;
}
div.scrollmenu a:hover {
background-color: #777;
}
</style>
</head>
<body>
<div class="scrollmenu">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="#support">Support</a>
<a href="#blog">Blog</a>
<a href="#tools">Tools</a>
<a href="#base">Base</a>
<a href="#custom">Custom</a>
<a href="#more">More</a>
<a href="#logo">Logo</a>
<a href="#friends">Friends</a>
<a href="#partners">Partners</a>
<a href="#people">People</a>
<a href="#work">Work</a>
</div>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.vertical-menu {
width: 200px;
height: 150px;
overflow-y: auto;
}
.vertical-menu a {
background-color: #eee;
color: black;
display: block;
padding: 12px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: #ccc;
}
.vertical-menu a.active {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h1>Vertical Scroll Menu</h1>
<div class="vertical-menu">
<a href="#" class="active">Home</a>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
<a href="#">Link 5</a>
<a href="#">Link 6</a>
<a href="#">Link 7</a>
<a href="#">Link 8</a>
<a href="#">Link 9</a>
<a href="#">Link 10</a>
</div>
</body>
</html>
Output:
6.4.13. Side Bar Menu:
The side bar menu displays a menu on the side of the web page.
Code:
<html>
<head>
<style>
.sidebar
{
height: 100%;
width:100px;
position:fixed;
background-color: pink;
padding-top:20px;
}
.sidebar a
{
text-deocration:none;
font-size:20px;
color:red;
display:block;
}
.sidebar a:hover
{
color:white;
}
.main
{
margin-left:160px;
padding:0px 10px;
}
</style>
</head>
<body>
<div class="sidebar">
<a href="#home"> Home</a>
<a href="#vision">Vision </a>
<a href="#mission"> Mission</a>
<a href="#prog">Programs</a>
</div>
<div class="main">
<h2> Side bar Menu </h2>
</div>
</body>
</html>
Output:
● A sophisticated visitor can access the cache and thereby gain access to the web
page source code.
● However, you can place obstacles in the way of a potential peeker. First, you can
disable use of the right mouse button on your site so the visitor can't access the
View Source menu option on the context menu. This hide both your HTML code
and your JavaScript from the visitor. Nevertheless, the visitor can still use the View
menu's Source option to display your source code. In addition, you can store your
JavaScript on your web server instead of building it into your web page. The
browser calls the JavaScript from the web server when it is needed by your web
page.
● Using this method, the JavaScript isn't visible to the visitor, even if the visitor views
the source code for the web page.
The following example shows you how to disable the visitor's right mouse button while
the browser displays your web page. All the action occurs in the JavaScript that is defined
in the <head> tag of the web page.
<html>
<head>
<script>
window.onload = function()
{
document.addEventListener("contextmenu", function(e)
{
e.preventDefault();
}, false);}
</script>
<body>
<h3>Right click on screen,Context Menu is disabled</h3>
</body>
</html>
Syntax
event.preventDefault()
<html>
<body>
<a id="myAnchor" href="https://w3schools.com/">Go to W3Schools.com</a>
<script>
document.getElementById("myAnchor").addEventListener("click", function(event){
event.preventDefault()
});
</script>
</body>
</html>
6.5.1.2 Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external file on your web
server. The external file should have the .js file extension. The browser then calls the
external fi le whenever the browser encounters a JavaScript element in the web page. If
you look at the source code for the web page, you'll see reference to the external .js file,
but you won't see the source code for the JavaScript.
The next example shows how to create and use an external JavaScript fi le. First you must
tell the browser that the content of the JavaScript is located in an external fi le on the web
server rather than built into the web page. You do this by assigning the fi le name that
contains the JavaScript to the src attribute of the <script> tag.
Next, you need to define empty functions for each function that you define in the external
JavaScript file.
webpage.html
<html>
<head>
<script src="mycode.js" languages="javascript" type="text/javascript">
</script>
<body>
<h3> Right Click on screen, Context Menu is disabled</h3>
</body>
</html>
mycode.js
window.onload=function()
{
document.addEventListener("contextmenu", function(e)
{
e.preventDefault();
}, false);
}
6.5.2 Concealing Your E-mail Address
● Many of us have endured spam at some point and have probably blamed every
merchant we ever patronized for selling our e-mail address to spammers.
● While e-mail addresses are commodities, it's likely that we ourselves are the
culprits who invited spammers to steal our e-mail addresses.
● Here's what happens: Some spammers create programs called bots that surf the
● Net looking for e-mail addresses that are embedded into web pages, such as those
placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack.
● This technique places developers between a rock and a hard place. If they place
their e-mail addresses on the web page, they might get slammed by spammers.
● If they don't display their e-mail addresses, visitors will not be able to get in touch
with the developers.
● The solution to this common problem is to conceal your e-mail address in the
source code of your web page so that bots can't find it but so that it still appears on
the web page.
● Typically, bots identify e-mail addresses in two ways: by the mailto: attribute that
tells the browser the e-mail address to use when the visitor wants to respond to
the web page, and by the @ sign that is required of all e-mail addresses. Your job is
to confuse the bots by using a JavaScript to generate the e-mail address
dynamically. However, you'll still need to conceal the e-mail address in your
JavaScript, unless the JavaScript is contained in an external JavaScript file, because
a bot can easily recognize the mailto: attribute and the @ sign in a JavaScript.
● Bots can also easily recognize when an external file is referenced.
● To conceal an e-mail address, you need to create strings that contain part of the
e-mail address and then build a JavaScript that assembles those strings into the
e-mail address, which is then written to the web page.
● The following example illustrates one of many ways to conceal an e-mail address.
● It also shows you how to write the subject line of the e-mail. We begin by creating
four strings:
• The first string contains the addressee and the domain along with symbols
&, *, and _ (underscore) to confuse the bot.
• The second and third strings contain portions of the mailto: attribute
name. Remember that the bot is likely looking for mailto:
• The fourth string contains the subject line. As you'll recall from your
HTML training, you can generate the TO, CC, BCC, subject, and body
of an e-mail from within a web page.
● You then use these four strings to build the e-mail address. This process starts by
using the replace() method of the string object to replace the & with the @ sign and
the * with a period (.). The underscores are replaced with nothing, which is the
same as simply removing the underscores from the string.
● All the strings are then concatenated and assigned to the variable b, which is then
assigned the location attribute of the window object. This calls the e-mail program
on the visitor's computer and populates the TO and Subject lines with the strings
generated by the JavaScript.
<html >
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress()
{
var x = 'abcxyz*c_o_m'
var y = 'mai'
var z = 'lto'
var s = '?subject=Customer Inquiry'
x = x.replace('&','@')
x = x.replace('*','.')
x = x.replace('_','')
x = x.replace('_','')
var b = y + z +':'+ x + s
window.location=b;
}
</script>
</head>
<body>
<input type="button" value="send" onclick="CreateEmailAddress()">
</body>
</html>
6.6 Frameworks of JavaScript and its application
Frameworks are more adaptable for the designing of websites, and hence, most of the
website developers prefer it. JavaScript frameworks are a type of tool that makes working
with JavaScript easier and smoother. These frameworks also make it possible for the
programmer to code the application as a device responsive.
Following are the most used framework of JavaScript:
1) React
React is not among the earliest disruptive JavaScript-based Web frameworks. But it is
the most disruptive and influential JavaScript-based Web framework. Jordan Walke and a
group of Facebook Engineers created React in 2013 as a Component-based Web
Framework with one-way data flow and changed the Front-end Web Development
forever. It also introduced many other concepts like functional, declarative
programming, immutable state, which was uncommon in Front-end development. The
other breakthrough of React was to introduce the Virtual DOM, which gives better user
experience and performance gain.
Features
2. Node.js
Features:
● It is swift:
The library of Node.js is fast when it comes to code execution, as it is built on the
V8 JavaScript engine of Google Chrome.
● I/O is asynchronous and Event-Driven:
All the APIs are asynchronous, which means that its server does not wait for the API
to come back with data. Here the server calls the APIs one by one and keeps
moving to the next one while using a notification mechanism of Events to generate
a response from the API, called previously. This makes it fast too.
● Single-threaded:
Node.js, along with event looping, follows a single-threaded model.
● Highly scalable:
Node.js follows an event mechanism that makes it possible for the server to
respond in a non-blocking manner, which eventually makes it scalable.
● No buffering:
When it comes to uploading audio and video files, Node.js cuts down the
processing time significantly. It does not buffer any data, and here the application
gets out the data in chunks.
● Open source:
Being open-source, Node.js's community has come up with several amazing
models that can be used to add better capabilities to the Node.js applications.
● License:
It has been released under MIT license.
3. Vue.js
In modern days where Web frameworks are backed by Giant Tech companies, Vue.js is an
exception. In 2014, an ex-Google Engineer Evan You decided to combine the good parts of
AngularJS (View Layer) and the good parts of React (Virtual DOM) and created Vue.js.
Today, Vue.js is one of the most popular JavaScript-based Web frameworks. One of the
key design goals of Evan You was to lower the barrier into JavaScript-based front-end
development. Vue.js is one of the easiest Front-end frameworks where developers can
write SPA applications with minor effort.
Developers can use Vue.js as an End-to-End framework with Routing, State management
like Angular, or as only a view layer like React. It also offers Angular like two-way
data-binding with additional Reactivity and React like rendering using Virtual DOM.
Features:
● Virtual DOM: Vue.js utilizes virtual DOM. Virtual DOM is a clone of the principal
DOM element. The virtual DOM absorbs every change intended for the DOM
presents in the form of JavaScript data structures, which are compared with the
original data structure.
● The viewers view final changes that reflect in the real DOM. The method is creative
and cost-effective; also, the changes are done quickly.
● Data Binding: This feature facilitates to manipulate or assign values to HTML
attributes., change the style, assign classes with v-bind available, which is a binding
directive.
● CSS Transitions and Animations: This feature provides several methods to apply a
transition to HTML elements when added, updated, or removed from the DOM. Its
features consist of a built-in component that wraps the element responsible for
returning the transition effect.
● Template: It provides HTML-based templates that bind the DOM with the Vue.js
instance data. The templates are compiled into Virtual DOM Render functions. A
developer can use the render functions template and can replace the template with
the render function.
● Methods: We use methods when an event occurs that isn’t necessarily related to
the instance data being mutated or want to change a component’s state. Methods
do not keep records of any dependencies but can take arguments.
● Complexity: Vue.js is simpler in terms of API and design. A web developer builds
simple applications in a single day.
4. Angular
In AngularJS, Google had created one of the earliest hot JavaScript-based Front-end
frameworks in 2010. But once Facebook released React, it exposed the design flaws of
AngularJS, and it quickly became an outdated framework. As a result, the Google team has
created an entirely new SPA framework and released it as Angular in 2016. Although
Angular and AngularJS have similar names, in reality, they are two different frameworks.
Unlike React, it is an end-to-end Framework with “Out-of-the-box” support of everything
one needs to develop an Enterprise-grade Web App. Also, Angular is the first significant
framework that has embraced TypeScript and played a considerable role in making
TypeScript popular.
Features:
● Angular.js is an end-to-end framework with “out of the box” support to develop
Enterprise Application. In Angular CLI, it has one of the best Command-Line Tool in
the JavaScript landscape.
● With TypeScript and separating the template from styling and business logic, it is
especially suited for the enterprise-grade large code-base.
● It is inherently the most secure Front-end framework with built-in features like DOM
sanitization.
● Although Google is not backing Angular the same way as Facebook is backing React, it
is still putting enough resources so that Angular remains an attractive and innovative
framework. Recently it has added Lazy Loading, Differential loading to improve
loading time of modules.
● In Angular 9, it releases a new rendering Engine Ivy to improve startup time, response
time, and to reduce bundle size.
5. Express
6. Next.js
React is a very unopinionated framework where React-Core just offers the view layer.
There was always a need for an end-to-end, opinionated framework based on React. Tim
Neutkens and a group of Software Engineers from the Dutch company Zeit has created
Next.js as an end-to-end, higher-level Web Framework on top of React and Node.js.
Next.js offers both Server-Rendered and Static Web sites for Web, Desktop, and Mobile
devices.
Features:
● Next.js is built upon the two most popular and battle-hardened JavaScript
frameworks: React and Node.js.
● It also offers “Build once, runs everywhere,” i.e., a Next.js can run on Web, Mobile, and
Desktop.
● Next.js offers excellent Server-Side rendering with exceptional SEO support and fast
startup.
● It offers automatic code splitting and filesystem-based routing.
● It also supports easy-to-use data fetching and built-in CSS support.
7.Meteor
Features:
● Meteor is a full-stack framework to develop the complete stack:
Frontend-to-Backend.
● For front-end development, it has its own template engine. But developers can use
Meteor with other popular front-end frameworks like Angular, React, Vue.js or Svelte.
● It is a cross-platform framework and can develop an application for Web, Mobile, and
Desktop.
● Meteor has integrated JavaScript stack, which enables different integrating
technologies (e.g., MongoDB database, React front-end) with minimum effort.
8. Svelte
In 2016, a Guardian Software Engineer Rich Harris had the groundbreaking idea to develop
a JavaScript framework with no framework-specific Runtime and released Svelte. The idea
was to use the Svelte compiler, which would compile framework-specific code to plain
JavaScript, HTML, CSS, and render the compiled code to the browser. Although the
concept was not new in software development, it was uncharted territory in Front-end
development. The other significant contribution of Svelte is to add first-class support of
reactivity, which leads to faster, improved performance without Virtual DOM. Today, it is
arguably the hottest Front-end framework with tremendous traction and interest in the
industry.
Features:
● It is a compile-time framework and does not need any framework-specific runtime. It
has the smallest bundle size among all frameworks.
● Svelte performs the DOM rendering via reactive programming, which is faster than
Virtual DOM most times. As a result, Svelte gives the fastest rendering among all
frameworks.
● Svelte is just a View layer like React-Core, and it is an unopinionated framework.
● Svelte supports both client-side and server-side rendering with excellent SEO
support.
● Developers can use Svelte to develop a Web app, Cross-platform Mobile App
development, or Desktop app development.
9. Koa
In 2013, the core members of Express.js led by TJ Holowaychuk had created Koa as
a lightweight, modern, expressive, and robust middleware framework for Web
Applications and APIs. Koa is hugely modular with tiny Core with no middleware.
However, middleware is available as separate modules.
Features:
● Koa has a lightweight, smaller Core with no out-of-the-box Middleware bundle.
● Koa has a highly modular architecture and offers pluggable middleware Modules.
● Koa supports cascading middleware in a stack-like manner, which allows to perform
actions downstream then and manipulate the response upstream.
● Koa uses async/await instead of callback and supports cleaner, expressive code with
better error handling.
● In terms of performance, it outperforms Express.js.
10. Ember.js.
Inspired by the Ruby on Rails principle “Convention over Configuration,” Yehuda
Katz from Apple has created Ember.js as a highly opinionated, end-to-end framework in
2012. Ember.js is a strictly backward compatible framework introducing no significant
breaking changes since its inception. Where other frameworks from that era (Backbone.js,
AngularJS) are diminishing in popularity, Ember.js is still giving a reliable, productive
framework to fulfill the need of modern Front-end development.
Features:
● End-to-end opinionated cohesive framework focusing on “Convention over
Configuration.”
● Instead of one Tech giant, Ember is backed by several Tech Giant like LinkedIn, Yahoo.
As a result, it is not driven by one corporation’s needs.
● Ember’s Data library is the best to access data across multiple sources at once, set up
asynchronous relationships.
● In Ember CLI, it has the best CLI among all JavaScript frameworks, which helps to
scaffold and generating all the necessary codes with the right structure, including all
dependencies.
● In its latest release Ember Octane, it has introduced HTML first and component first
approach with improved support for state management and reactivity.
11. Backbone.js
Aurelia framework is the latest version of JavaScript, which can be used to implement any
interface. It is the next generation of the framework for developing far more robust
websites. The framework of Aurelia can extend the HTML for various purposes, including
data binding. Also, its modern architecture ensures that the purpose of toll is for
interpretation client-side and server-side at a time.
Features:
● Components: Components are building blocks of the Aurelia framework and are
composed of JavaScript view-model pairs and HTML views.
● Web Standards: It is one of the cleanest modern frameworks. It completely focuses
on web standards without unnecessary abstractions.
● Extensible: The framework facilitates an easy way to integrate with the other
needed tools.
● Commercial Support: This framework offers commercial and enterprise support.
● License: Aurelia is open-sourced and licensed under MIT license.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var subjectObject = {
"Front-end": {
"HTML": ["Links", "Images", "Tables", "Lists"],
"CSS": ["Borders", "Margins", "Backgrounds", "Float"],
"JavaScript": ["Variables", "Operators", "Functions", "Conditions"]
},
"Back-end": {
"PHP": ["Variables", "Strings", "Arrays"],
"SQL": ["SELECT", "UPDATE", "DELETE"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("subject");
var topicSel = document.getElementById("topic");
var chapterSel = document.getElementById("chapter");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
chapterSel.length = 1;
topicSel.length = 1;
//display correct values
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() {
//empty Chapters dropdown
chapterSel.length = 1;
//display correct values
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>HTML and CSS Slideshow</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 5%;
text-align: center;
font-size: 50;
}
#slideshow {
overflow: hidden;
height: 510px;
width: 728px;
margin: 0 auto;
}
.slide {
float: left;
height: 510px;
width: 728px;
}
/* Add animation to the slides */
.slide-wrapper {
.slide:nth-child(1) {
background: green;
}
.slide:nth-child(2) {
background: pink;
}
.slide:nth-child(3) {
background: red;
}
.slide:nth-child(4) {
background: yellow;
}
@keyframes slide {
<body>