0% found this document useful (0 votes)
5 views

Complete JavaScript

Uploaded by

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

Complete JavaScript

Uploaded by

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

What is Scripting Language?

It is loosely or weakly typed or light weight programming. Scripts are becoming more popular due to
the emergence of web-based applications.

Advantages of Scripting Languages:

1 Easy to learn and use

2 Minimum programming knowledge or experience required

3 Allow complex tasks to be performed in relatively few steps

4 Editing and running code is fast.

Limitations of Scripting Languages:

1. Because of code executes on the users computer, in some cases it can be exploited for malicious
purposes. (Security Issues)

2. Not always able to work across different browsers. (Inconsistant)

Types of Scripts:

Scripts are Classified into the following two types:

1. Client Side Scripts

2. Server Side Scripts

1. Client Side Scripts

The script which is running within the browser is called as client side scripting.

Example:

1. Live Script

2. JavaScript

3. Type Script

4. VB Script

5. AJAX (Asynchronous Javascript and XML)


6. HTML/DHTML/CSS

7. Dart (Google)

8. Brython

2. Server Side Scripts

The Script which is running within the web server is called as server side scripting.

Example:

PYTHON ==> Simple HTTP Server (NO-1),WSGI

ASP ==>IIS (Internet Information Services)

JSP ==>Apache Tomcat, Sun Java System Web Server, Nginx

PHP ==> Apache http,Nginx,WampServer

RUBY==> Puma, WebRick,Unicorn

NodeJS ==> Server Side Java Script, Apache, IIS

What is JavaScript? Who Developed?

JavaScript is the world's most popular programming language.JavaScript is the programming


language of the Web. JavaScript is easy to learn. It was created by Brendan Eich at Netscape in
December 1995 under the name of LiveScript. JavaScript’s official name is ECMAScript.

(European Computer Manufacturer's Association). JavaScript became an ECMA standard (ECMA-


262/ES1)

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

Every version of JavaScript:

1 The Original JavaScript ES1 ES2 ES3 (1997-1999)


2 The First Main Revision ES5-ECMAScript (2009)

3 The Second Revision ES6- ECMAScript (2015)

4 The Yearly Additions (2016, 2017)

5. ECMAScript 2016/2017 was not called ES7/ES8

Features of JavaScript

1. It gives HTML designers a programming tool

2. JavaScript can react to events

3. Detecting the user's browser, OS, screen size,etc..!!

4. JavaScript can be used to validate data

5. Open and cross-platform

What JavaScript can Do?

1. JavaScript Can Change HTML Content

2. JavaScript Can Change HTML Attribute Values

3. JavaScript Can Change HTML Styles (CSS)

4. JavaScript Can Hide HTML Elements

5. JavaScript Can Show HTML Elements

Code editors:

A code editor is the place where programmers spend most of their time. There are two main types
of code editors: IDEs and lightweight editors.

IDE:

Integrated Development Environment refers to a powerful editor with many features that usually
operates on a “whole project.” It is a full-scale “development environment.”

1 Visual Studio Code (cross-platform, free).

2 WebStorm (cross-platform, paid).


Lightweight Editors:

"Lightweight Editors" are not as powerful as IDEs, but they’re fast, elegant and simple.

1 Atom (cross-platform, free).

2 Sublime Text (cross-platform, shareware).

3 Notepad++ (Windows, free).

4 Vim and Emacs are also cool if you know how to use them.

JavaScript Syntax:

JavaScript consists of JavaScript statements that are placed within the following:

Syntax1:

<script type="text/javascript" language="javascript">

Statements;

Statements;

Statements;

</script>

Syntax2:

<script language="javascript">

Statements;

Statements;

Statements;

</script>

Syntax3:

<script>
Statements;

Statements;

Statements;

</script>

Example:

<!DOCTYPE html>

<head>

<script>

document.write("Welcome to JavaScript");

</script>

</head>

Example:

<!DOCTYPE html>

<head>

<script>

document.write("Welcome to LiveScript");

document.write("Welcome to JavaScript");

</script>

</head>

Example:

<!DOCTYPE html>

<head>

<script>

document.write("Welcome to LiveScript");
document.write("<br/>")

document.write("Welcome to JavaScript");

</script>

</head>

Single and Double quotes in JavaScript

You can write the above code with single quotes too and it will give the same result. However, if the
text contains double quotes that have to be displayed, you should use single quotes to surround the
text as in:

Example:

<!doctype html>

<head>

<script>

document.write("Welcome to JavaScript");

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

document.write('Welcome to JavaScript');

</script>

</head>

Example:

<!doctype html>

<head>

<script>

document.write("Welcome to JavaScript");

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

document.write('Welcome to JavaScript');

document.write("<br/>");
document.write("Welcome to 'Java' Script");

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

document.write('Welcome to "Java" Script');

</script>

</head>

Example:

<!doctype html>

<head>

<script>

document.write("Welcome to "Java" Script");

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

document.write('Welcome to 'Java' Script');

</script>

</head>

Example:

<!doctype html>

<head>

<script>

document.write("Welcome to \"Java\" Script");

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

document.write('Welcome to \'Java\' Script');

</script>

</head>

Difference between document.write() and window.document.write()


There is no difference between the two. Remember, the window object is the highest level object. It
can contain other objects and their methods. Hence, document is a object contained inside the
window object; write() is a method of the document object .

Example:

<!doctype html>

<head>

<script>

window.document.write("Welcome to JavaScript")

document.write("<br>")

document.write("Good Bye...!!")

</script>

</head>

Writing into the HTML output using document.write().

The write() method writes HTML expressions or JavaScript code to a document.

Syntax

document.write(exp1,exp2,exp3,...)

Example:

<!doctype html>

<body>

<script type='text/javascript'>

document.write("<h1>Hello World!</h1><p>Have a nice day!</p>");

</script>

</body>
Document writeln() Method

The writeln() method is identical to the write() method, with the addition of writing a new space
character after each statement.

Syntax

document.writeln(exp1,exp2,exp3,...)

Example:

<!doctype html>

<body>

<pre>

<script type='text/javascript'>

document.write("Hello World!");

document.write("Have a nice day!");

</script>

</pre>

<pre>

<script type='text/javascript'>

document.writeln("Hello World!");

document.writeln("Have a nice day!");

</script>

</pre>

</body>

JavaScript Statements

A JavaScript program is a list of logical statements. In HTML, JavaScript programs are executed by
the web browser. JavaScript statements are composed of Values, Operators, Expressions, Keywords,
and Comments.
Example:

<!DOCTYPE html>

<body>

<p id="msg"></p>

<script type='text/javascript'>

document.getElementById("msg").innerHTML = "Hello Raju Sir.";

</script>

</body>

JavaScript Code

JavaScript code is a sequence of JavaScript statements. Each statement is executed by the browser in
the sequence they are written.

This example will write a heading and two paragraphs to a web page:

Example

<!doctype html>

<head>

<script type="text/javascript">

document.write("<h1>This is a heading</h1>");

document.write("<p>This is a paragraph.</p>");

</script>

</head>

JavaScript Blocks

JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {, and
end with a right curly bracket }. The purpose of a block is to make the sequence of statements
execute together.
This example will write a heading and two paragraphs to a web page:

Example

<!doctype html>

<head>

<script type="text/javascript">

document.write("<h1>This is a heading</h1>");

document.write("<p>This is a paragraph.</p>");

document.write("<p>This is another paragraph.</p>");

</script>

</head>

Comments in JAVASCRIPT:

Comments are non-executable statements or ignore statements. Comments are using to declare
customize statements or user defined statements within the source code.

In JavaScript comments are classified into the following types.

1. Single line comments

2. Multiline comments

1. Single line comments

These comments are applicable to a specific line or statement. It is always denoted with (//) double
forward slash.

Syntax:

// This is a comment
Example:

<!doctype html>

<head>

<script type='text/javascript'>

//document.write("Hello Comment");

//document.write("Thank U");

</script>

</head>

O/P: Blank Page

2. Multiline comments:

These comments are applicable one or more lines. It is always denoted with /* */

Syntax:

/*

Statements

Statements

*/

Example:

<!doctype html>

<head>

<script>

/* document.write("Welcome to JS");

document.write("Thank U");

document.write("Good Bye"); */
</script>

</head>

JavaScript Values

The JavaScript syntax defines two types of values:

Fixed values => Fixed values are called Literals/Constants.

Variable values => Variable values are called Variables/Identifier.

JavaScript Literals

1. Numbers are written with or without decimals:

10.50; 1001

Example:

<!DOCTYPE html>

<body>

<script>

var a=10

document.write("The Value is: "+a +"<br>")

var a=9.99

document.write("The Value is: "+a)

</script>

</body>

2. Strings are text, written within double or single quotes:

"JavaScrpt"; 'JavaScript'

JavaScript Variables
In a programming language, variables are used to store data values. JavaScript uses the var keyword
to declare variables. An equal sign is used to assign values to variables.

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript Variables</h2>

<script>

var x; x = 6;

document.write("The Value is: "+x +"<br>")

</script>

</body>

JavaScript and Camel Case

Programmers have used different ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.


Semicolons are Optional:

Simple statements in JavaScript are generally followed by a semicolon character.

Example:

<!doctype html>

<script>

var1 = 10

var2 = 20

</script>

Example:

<!doctype html>

<script>

var1 = 10; var2 = 20;

</script>

Example:

<!DOCTYPE html>

<body>

<script>

document.write("Hello Welcome to JS");document.write("Hello Welcome to JS")

</script>

</body>

Note: It is a good programming practice to use semicolons.


JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

Example:

<!DOCTYPE html>

<body>

<script>

var Name = "RajuSir";

var Name="RajuSir";

</script>

</body>

JavaScript is Case Sensitive

A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is
not the same as "myvar".

Example:

<!DOCTYPE html>

<body>

<script>

var a=10;A=100;b=1;B=100

document.write(a+A)

document.write("<br/>")

document.write(b-B)

</script>

</body>

JavaScript Place in HTML File:


There is a flexibility given to include JavaScript code anywhere in HTML document. But there are
following most preferred ways to include JavaScript in your HTML file.

1. Script in <head>...</head> section.

2. Script in <body>...</body> section.

3. Script in <body>...</body> and <head>...</head> sections.

4. Script in and external file and then include in <head>...</head> section.

Using an External JavaScript

JavaScript can also be placed in external files. External JavaScript files often contain code to be used
on several different web pages. External JavaScript files have the file extension .js.

NOTE:

External script cannot contain the <script></script> tags!

NOTE:

To use an external script, point to the .js file in the "src" attribute of the <script> tag:

1. Step1 --> Create JavaScript File

document.write("<h1>Wecome to JS External Programming!!</h1>");

document.write("<b>Bye...!!");

Save with myscript.js Extension....!!

2. Step2 --> Create HTML file

<html>

<head>

<script type="text/javascript" src="myscript.js"></script>

</head>
<body>

</body>

</html>

JavaScript Popup Boxes

JavaScript has three kind of popup boxes:

1. Alert box

2. Confirm box

3. Prompt box.

Alert Box

An alert box is often used if you want to make sure information comes through the user. When an
alert box pops up, the user will have to click "OK" to proceed.

Syntax

alert("Message");

Example:

<html>

<head>

<title>Alert box</title>

<script type="text/javascript">

alert("Click OK to Proceed");

alert("Naresh i Technologies");

</script>

</head>

<body>

</body>
</html>

How to write text on multiple lines in an alert box?

We can't use the <br> tag here, as we did in write(), because alert() is a method of the window
object that cannot interpret HTML tags. Instead we use the new line escape character.

Escape characters in JavaScript:

Escape characters are characters that can be interpreted in some alternate way then what we
intended to. To print these characters as it is, include backslash ‘\’ in front of them.

Code Result

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Horizontal Tabulator

\v Vertical Tabulator

\\ Backslash

Example:

<script>

alert("JavaScript\nis\na\nclient-side\nprogramming\nlanguage");

</script>

Example:

<script>

alert("1\n\t2\n\t\t3");

</script>

JavaScript Popup Boxes


JavaScript has three kind of popup boxes:

1. Alert box

2. Confirm box

3. Prompt box.

Alert Box

An alert box is often used if you want to make sure information comes through the user. When an
alert box pops up, the user will have to click "OK" to proceed.

Syntax

alert("Message");

Example:

<html>

<head>

<title>Alert box</title>

<script type="text/javascript">

alert("Click OK to Proceed");

alert("Naresh i Technologies");

</script>

</head>

<body>

</body>

</html>

How to write text on multiple lines in an alert box?

We can't use the <br> tag here, as we did in write(), because alert() is a method of the window
object that cannot interpret HTML tags. Instead we use the new line escape character.
Escape characters in JavaScript:

Escape characters are characters that can be interpreted in some alternate way then what we
intended to. To print these characters as it is, include backslash ‘\’ in front of them.

Code Result

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Horizontal Tabulator

\v Vertical Tabulator

\\ Backslash

Example:

<script>

alert("JavaScript\nis\na\nclient-side\nprogramming\nlanguage");

</script>

Example:

<script>

alert("1\n\t2\n\t\t3");

</script>

Example:

<html>

<head>

<script type="text/javascript">

function show_alert()
{

alert("I am an alert box!");

</script>

</head>

<body>

<input type="submit" onclick="show_alert()" value="Show alert box" />

</body>

</html>

Confirm Box:

A confirm box is often used if you want the user to verify or accept something. When a confirm box
pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the
box returns true. If the user clicks "Cancel", the box returns false.

Syntax

confirm("Message");

Example:

<html>

<head>

<title>Confirm box</title>

<script type="text/javascript">

confirm("Click OK or Cancel");

</script>

</head>

<body>

</body>
</html>

Example:

<script>

xyz=confirm("Select OK or Cancel");

if (xyz==true)

alert("u selected OK");

else

alert("u selected cancel");

</script>

<body>

</body>

Example:

<html>

<head>

<script type="text/javascript">

function show_confirm()

var r=confirm("Press a button");

if (r==true)

alert("You pressed OK!");


}

else

alert("You pressed Cancel!");

</script>

</head>

<body>

<input type="button" onclick="show_confirm()" value="Show confirm box" />

</body>

</html>

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page. When a
prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an
input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
returns null.

Syntax

prompt("sometext","defaultvalue");

Example:

<html>

<head>

<title>Prompt box</title>

<script type="text/javascript">

var x=prompt("Enter the number","20");

alert("The Value that u entered is "+x);


</script>

</head>

<body>

</body>

</html>

Example2:

<html>

<head>

<script type="text/javascript">

function show_prompt()

var name=prompt("Please enter your name","Raju");

if (name!=null && name!="")

document.write("<p>Hello " + name + "! How are you today?</p>");

</script>

</head>

<body>

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body>

</html>

JavaScript Variables/identifiers:

A JavaScript variable is simply a name of storage location. There are some rules while declaring a
JavaScript variable.
1 Names can contain letters, digits, underscores, and dollar signs.

2 Names must begin with a letter

3 Names can also begin with $ and _ (but we will not use it in this tutorial)

4. Reserved words (like JavaScript keywords) cannot be used as names

5. You declare JavaScript variables with the var keyword

6. Names are case sensitive (y and Y are different variables)

Correct JavaScript variables

var x = 10;

var _value="NareshIT";

Incorrect JavaScript variables

var 1abc=30;

var *a=320;

Example:

<!doctype html>

<head>

<script>

var x = 10;

var y = 20;

var z=x+y;

document.write("The Result is: "+z);

</script>

</head>
One Statement, Many Variables

You can declare many variables in one statement. Start the statement with var and separate the
variables by comma.

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript Variables</h2>

<script>

var person = "SARA", bname = "Yamaha", price = 2000;

document.write(bname +"<br>")

document.write(price +"<br>")

</script>

</body>

Value = undefined

A variable declared without a value will have the value undefined.

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript Variables</h2>

<script>

var bname;

document.write(bname)

</script>

</body>
Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value.

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript Variables</h2>

<p id="txt"></p>

<script>

var bname = "Yamaha";

var bname;

document.getElementById("txt").innerHTML = bname;

</script>

</body>

JavaScript Dollar Sign $

A letter (A-Z or a-z), A dollar sign ($), Or an underscore (_)

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript $</h2>

<script>

var $ = 1;

var $myMoney = 4;

document.write( $ + $myMoney)
</script>

</body>

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Example:

<!DOCTYPE html>

<body>

<h2>JavaScript _</h2>

<script>

var _x = 2;

var _y = 5;

document.write(_x + _y);

</script>

</body>

Using let and const (ES6)

Using the var keyword was the only way to declare a JavaScript variable. JavaScript (ES6) allows the
use of the const keyword to define a variable that cannot be reassigned, and the let keyword to
define a variable with restricted scope.

JavaScript Block Scope

Variables declared with the var keyword cannot have Block Scope. Variables declared inside a block
{} can be accessed from outside the block.

Example

var x = 5;
}

// x CAN be used here

Example:

<!doctype html>

<head>

<script>

var x = 5;

document.write(x)

// x CAN be used here

document.write(x)

</script>

</head>

NOTE:

Before ES2015 JavaScript did not have Block Scope. Variables declared with the let keyword can have
Block Scope. Variables declared inside a block {} cannot be accessed from outside the block:

Example

let x = 5;

// x can NOT be used here

Example:

<head>
<script>

let x = 5;

document.write(x)

// x CAN be used here

document.write(x)

</script>

</head>

Redeclaring Variables

Redeclaring a variable using the var keyword can impose problems. Redeclaring a variable inside a
block will also redeclare the variable outside the block:

Example:

<!DOCTYPE html>

<body>

<h2>Declaring a Variable Using var</h2>

<script>

var x = 100;

// Here x is 100

var x = 20;

// Here x is 20

// Here x is 20

document.write(x);

</script>
</body>

JavaScript const

In JavaScript we can declare constants using 'const' keyword. These are literals, never allow to
change.

Assigned when Declared

JavaScript const variables must be assigned a value when they are declared:

InValid Declaration

const PI;

PI = 3.14159265359;

Valid Declaration

Correct

const PI = 3.14159265359;

Example:

<!DOCTYPE html>

<body>

<script>

// Declaring variables

let name = "Subba Raju Sir";

let age = 43;

let isStudent = true;

// Printing variable values

document.write(name + "<br>");
document.write(age + "<br>");

document.write(isStudent + "<br>");

// Declaring constant

const PI = 3.14;

// Printing constant value

document.write(PI); // 3.14

// Trying to reassign

PI = 10; // error

</script>

</body>

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope. The x declared in the
block, in this example, is not the same as the x declared outside the block:

Example:

<!DOCTYPE html>

<body>

<h2>Declaring a Variable Using const</h2>

<p id="txt"></p>

<script>

var x = 100;

// Here x is 100

const x = 20;
// Here x is 20

// Here x is 100

document.write(x);

</script>

</body>

JavaScript const

In JavaScript we can declare constants using 'const' keyword. These are literals, never allow to
change.

Assigned when Declared

JavaScript const variables must be assigned a value when they are declared:

InValid Declaration

const PI;

PI = 3.14159265359;

Valid Declaration

Correct

const PI = 3.14159265359;

Example:

<!DOCTYPE html>

<body>

<script>

// Declaring variables

let name = "Subba Raju Sir";

let age = 43;


let isStudent = true;

// Printing variable values

document.write(name + "<br>");

document.write(age + "<br>");

document.write(isStudent + "<br>");

// Declaring constant

const PI = 3.14;

// Printing constant value

document.write(PI); // 3.14

// Trying to reassign

PI = 10; // error

</script>

</body>

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope. The x declared in the
block, in this example, is not the same as the x declared outside the block:

Example:

<!DOCTYPE html>

<body>

<h2>Declaring a Variable Using const</h2>

<p id="txt"></p>

<script>
var x = 100;

// Here x is 100

const x = 20;

// Here x is 20

// Here x is 100

document.write(x);

</script>

</body>

Javascript Data Types

JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.

1. Primitive Data Types

2. Non Primitive(reference) Data Types

JavaScript is a dynamic type language, means you don't need to specify type of the variable because
it is dynamically used by JavaScript engine. You need to use var here to specify the data type. It can
hold any type of values such as numbers, strings etc.

Example:

var a=40;//holding number

var b="RajuSir";//holding string

1. Primitive Data Types

JavaScript has five primitive data types. These are the most simple forms of data we can use in JS
programming.
Data Type Description

String Represents sequence of characters e.g. "JS"

Number Represents numeric values e.g. 100

Boolean Represents boolean value either false or true

Undefined Represents undefined value

Null Represents null i.e. no value at all

JavaScript Strings

A string is a variable which stores a series of characters like "nit". A string can be any text inside
quotes. You can use single or double quotes:

Example

var name="nit";

var name='nit';

Example:

<!doctype html>

<head>

<script type="text/javascript">

document.write("Hello Welcome to JS Strings")

document.write("<br/>")

document.write('Hello Welcome to JS Strings')

</script>

</head>

Example:

<!doctype html>
<head>

<script type="text/javascript">

Str1="Hello",var Str2='World'

document.write("First String is: "+Str1)

document.write("<br/>")

document.write("Second String is: "+Str2)

</script>

</head>

Number Data Type

JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

Example

var x1=34.00; // Written with decimals

var x2=34; // Written without decimals

Example:

<!doctype html>

<head>

<script type="text/javascript">

var x=10;var y=20.99; var z=x+y;

var name="Naresh i Technologies";

document.write("The value of x is "+x);

document.write("<br>");

document.write("The value of y is "+y);

document.write("<br>");

document.write("The value of z is "+z);


document.write("<br>");

document.write(name+" is Leader in IT Training");

</script>

</head>

Boolean Data Type

The Boolean data type

The Boolean data type is used to represent a Boolean value. A Boolean value can be used to
represent data that is in either of two states.Booleans are often used in conditional testing.

The two Boolean values

true // equivalent to true, yes, or on

false // equivalent to false, no, or off

Example:

<!doctype html>

<head>

<script type="text/javascript">

var x=10;var y=20;

document.write("The value is: "+(x>y));

document.write("<br>");

document.write("The value is: "+(x<y));

</script>

</head>

Undefined

It is the value of a variable with no value.


Example

var x; // Now x is undefined

Example:

<!doctype html>

<head>

<script type="text/javascript">

var x;

document.write("The value is: "+x +"<br/>");

var y;

document.write("The value is: "+y);

</script>

</head>

null:

Variables can be emptied by setting the value to null;

Example:

var x=null; // Now x is null

Example:

<!doctype html>

<head>

<script type="text/javascript">

var x=null;

document.write("The value is: "+x +"<br/>");

var y=null;
document.write("The value is: "+y);

</script>

</head>

2. Non Primitive Data Types

Object:

Declaring Variables as Objects.When a variable is declared with the keyword "new", the variable is
declared as an object:

Syntax:

var name = new String();//String Object

var x =new Number();//Number Object

var y =new Boolean();//Boolean Object

Dynamic Types:

JavaScript has dynamic types. This means that the same variable can be used as different types:

Example

var x; // Now x is undefined

var x = 5; // Now x is a Number

var x = "RaaJ"; // Now x is a String

Example:

<!doctype html>

<body>

<script>

var x;

document.write(x +"<br/>");
var x=96;

document.write(x);

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

var x="Modern Java Script";

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

var x=null;

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

var x=true;

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

</script>

</body>

HTML <noscript> Tag

It is used to provide an alternate content for users that have disabled scripts in their browser or have
a browser that doesn’t support client-side scripting. It is a paired tag.

Syntax:

<noscript>..............</noscript>

Example:

<!doctype html>

<head>

<script>

document.write("Welcome to JavaScripting")

document.write("<br/>")

document.write("Welcome to JavaScripting")

</script>

</head>
<body>

<noscript>

<p>OOPs Script unable to execute on this web browser...!!</p>

</noscript>

</body>

JavaScript Operators

JavaScript operators are symbols that are used to perform operations on operands.There are
following types of operators in JavaScript.

1 Arithmetic Operators

2 Assignment Operators

3 JavaScript String Operators

4 JavaScript Incrementing and Decrementing Operators

5 JavaScript Logical Operators

6 JavaScript Comparison Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9


Example:

<!DOCTYPE html>

<body>

<script>

var x = 10;

var y = 4;

document.write(x + y); // display: 14

document.write("<br>");

document.write(x - y); // Prints: 6

document.write("<br>");

document.write(x * y); // Prints: 40

document.write("<br>");

document.write(x / y); // Prints: 2.5

document.write("<br>");

document.write(x % y); // Prints: 2

</script>

</body>

JavaScript Assignment Operators

The assignment operators are used to assign values to variables.


Operator Description Example Is The Same As

= Assign x=y x=y

+= Add and assign x += y x = x + y

-= Subtract and assign x -= y x=x-y

*= Multiply and assign x *= y x = x * y

/= Divide and assign quotient x /= y x=x/y

%= Divide and assign modulus x %= y x = x % y

Example:

<!DOCTYPE html>

<body>

<script>

var x; // Declaring Variable

x = 10;

document.write(x + "<br>"); // Prints: 10

x = 20;

x += 30;

document.write(x + "<br>"); // Prints: 50

x = 50;

x -= 20;

document.write(x + "<br>"); // Prints: 30

x = 5;

x *= 25;
document.write(x + "<br>"); // Prints: 125

x = 50;

x /= 10;

document.write(x + "<br>"); // Prints: 5

x = 100;

x %= 15;

document.write(x); // Prints: 10

</script>

</body>

JavaScript String Operators

There are two operators which can also used be for strings.

Operator Description Example Result

+ Concatenation str1 + str2 Concatenation of str1 and str2

+= Concatenation assignment str1 += str2 Appends the str2 to the str1

Example:

<!DOCTYPE html>

<body>

<script>

var str1 = "Hello";

var str2 = " World!";

document.write(str1 + str2 + "<br>"); // Outputs: Hello World!

str1 += str2;
document.write(str1); // Outputs: Hello World!

</script>

</body>

JavaScript Incrementing and Decrementing Operators

The increment/decrement operators are used to increment/decrement a variable's value.

Operator Name Effect

++x Pre-increment Increments x by one, then returns x

x++ Post-increment Returns x, then increments x by one

--x Pre-decrement Decrements x by one, then returns x

x-- Post-decrement Returns x, then decrements x by one

Example:

<!DOCTYPE html>

<body>

<script>

var x; // Declaring Variable

x = 10;

document.write(++x); // Prints: 11

document.write("<p>" + x + "</p>"); // Prints: 11

x = 10;

document.write(x++); // Prints: 10

document.write("<p>" + x + "</p>"); // Prints: 11

x = 10;

document.write(--x); // Prints: 9
document.write("<p>" + x + "</p>"); // Prints: 9

x = 10;

document.write(x--); // Prints: 10

document.write("<p>" + x + "</p>"); // Prints: 9

</script>

</body>

JavaScript Looping Statements:

Different Kinds of Loops

JavaScript supports different kinds of loops:

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

2 while - loops through a block of code while a specified condition is true

3 do/while - also loops through a block of code while a specified condition is true

4 for/in - loops through the properties of an object

for Loop

A for loop enables a particular set of conditions to be executed repeatedly until a condition is
satisfied.

Syntax:

for (initialization; test condition; iteration statement)

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

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

Example:

<!doctype html>
<body>

<script type="text/javascript">

for (i=1;i<=5;i++)

document.write("The number is " + i);

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

</script>

</body>

Example:

<!doctype html>

<body>

<script type="text/javascript">

for (i = 1; i <= 6; i++)

document.write("<h" + i + ">This is heading ");

document.write("</h" + i + ">");

</script>

</body>

JavaScript While Loop

There are two key parts to a JavaScript while loop:

1.The conditional statement which must be True for the while loop's code to be executed.

2.The while loop's code that is contained in curly braces "{ and }" will be executed if the condition is
True.
Syntax

while (variable<=endvalue)

code to be executed

code to be executed

Example1

<!doctype html>

<body>

<script type="text/javascript">

var i=1;

while (i<=5)

document.write("The number is " + i);

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

i++;

</script>

</body>

Example:

<!doctype html>

<head>

<script>

counter=0

while (counter < 5)


{

document.write("Counter: " + counter + "<br />")

++counter

</script>

</head>

do...while Loops

When you require a loop to iterate at least once before any tests are made, use a

do...while loop, which is similar to a while loop, except that the test expression is

checked only after each iteration of the loop.

Syntax

do

code to be executed

code to be executed

while (variable<=endvalue);

Example:

<!doctype html>

<head>

<script type="text/javascript">

var i = 1;

do

{
document.write("The number is " + i);

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

i++;

while (i <= 10);

</script>

</head>

Example:

<!doctype html>

<head>

<script>

count = 1

do

document.write(count + " times 7 is " + count * 7 + "<br />")

while (++count <= 7)

</script>

</head>

JavaScript Break and Continue Statements

The break Statement

The break statement will break the loop and continue executing the code that follows after the loop
(if any).

Example:

<!doctype html>
<body>

<script type="text/javascript">

var i=0;

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

if (i==3)

break;

document.write("The number is " + i);

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

</script>

</body>

The continue Statement

The continue statement will break the current loop and continue with the next value.

Example:

<!doctype html>

<body>

<script type="text/javascript">

var i=0;

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

if (i==3)

{
continue;

document.write("The number is " + i);

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

</script>

</body>

JavaScript for...in loop:

There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop
through an object's properties.

Syntax:

for (variablename in object)

statement or block to execute

statement or block to execute

Example: For In

<!doctype html>

<body>

<script type="text/javascript">

var pros;

document.write("Navigator Object Properties<br /> ");

for (pros in navigator)

document.write(pros +"<br/>");
}

</script>

</body>

Define Function?

A function is a block of code that will be executed only by an occurence of an event at that time
fuction is called. A function can called from anywhere within the HTML page. Function can define in
the beginning of the <head> Tag.

A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing same code again and again. This will help programmers to write
modular code. This benefit is also known as "code reusability".

Syntax

function functionName(parameters)

code to be executed

code to be executed

Example:

<!DOCTYPE html>

<html>

<title>Java-Script Functions...!!</title>

<script type="text/javascript">

//function body Part

//Logical Implementation Part

//This is Called Part

//Declaring Arguments

//Function is return type


function WishMe()

window.alert("Welcome to Functions...!!")

alert("FunctionsAreCodeReusability...!!")

</script>

</head>

<body>

<!--Function Calling Part -->

<!--Passing Parameters -->

<!--Tail Part of the function -->

<p>Click the Following button to call the function....!!</p>

<button onclick="WishMe()">ClickHere.!</button>

</body>

Example:

<!doctype html>

<head>

<script type="text/javascript">

function popup()

alert("Hello World")

</script>

</head>

<body>

<input type="button" onclick="popup()" value="popup">


</body>

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called arguments or
parameters. These arguments can be used inside the function. You can send as many arguments as
you like, separated by commas (,)

Syntax:

function myFunction(var1,var2)

JS Statements

JS Statements

JS Statements

The return Statement

The return statement is used to specify the value that is returned from the function. So, functions
that are going to return a value must use the return statement. A JavaScript function can have an
optional return statement.

Example:

<!doctype html>

<head>

<script type="text/javascript">

function myFunction()

return ("Hello world!");

</script>
</head>

<body>

<script type="text/javascript">

document.write(myFunction())

</script>

</body>

Example:

<!doctype html>

<head>

<script type="text/javascript">

function addition(x,y)

return x+y;

</script>

<script>

document.write("Addtion of two Number: "+addition(4,5));

</script>

Example:

<!doctype html>

<head>

<p>Click the button to call a function with arguments</p>

<script type="text/javascript">

function myFunction(name,job)

{
alert("Welcome " + name + ", the " + job);

</script>

<head>

<body>

<button onclick="myFunction('Subbaraju','SoftwareEngineer')">ClickMe</button>

</body>

Example:

<!doctype html>

<head>

<p>Click one of the buttons to call a function with arguments</p>

<script type="text/javascript">

function myFunction(name,job)

alert("Welcome " + name + ", the " + job);

</script>

</head>

<body>

<button onclick="myFunction('Smith','SQL Developer')">Click forSmith</button>

<button onclick="myFunction('Scott','Programmer')">Click for Scott</button>

</body>

The Lifetime of JavaScript Variables

Local JavaScript Variables


A variable declared within a JavaScript function becomes LOCAL and can only be accessed within
that function. (the variable has local scope). You can have local variables with the same name in
different functions.

Example:

<!doctype html>

<script>

function Scope_Local()

var x;

x = 5;

-------------

-------------

Example:

<!DOCTYPE html>

<html>

<title>Java-Script Functions...!!</title>

<script type="text/javascript">

function Display1()

//Local Scope Variables

//These are within the function

var a=10,b=20

document.write("The Result is: "+(a+b))

</script>
</head>

<body>

<button onclick="Display1()">HiTMe</button>

</body>

</html>

Global JavaScript Variables

Variables declared outside a function become GLOBAL, all scripts and functions on the web page can
access it. Global variables are deleted when you close the page.

Example:

<!DOCTYPE html>

<script type="text/javascript">

//Global Scope

b=1

function Display1()

//Local Scope Variables

//These are within the function

var a=10,b=20

document.write("The Result is: "+(a+b))

function Display2()

//Local Scope Variables

//These are within the function

var a=10

document.write("The Result is: "+(a+b))


}

</script>

</head>

<body>

<button onclick="Display1()">HiTMe</button>

<button onclick="Display2()">HiTMe</button>

</body>

Example:

<!doctype html>

<script>

//Global Scope

year = 1997;

function local_globalvariable ()

//LocalScope

month = 2;

local_globalvariable ();

document . write ("year=" + year + " and month="+ month);

</script>

Example:

<!doctype html>

<body>

<script>

//Global Scope
year = 2012;

function local_globalvariable()

//Local Scope

month = 8;

function local_global_variable()

//Local Scope

month = 9;

local_globalvariable();

document . write ("year=" + Year + " and month="+ month);

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

local_global_variable();

document . write ("year=" + Year + " and month="+ month);

</script>

</body>

BackGround Colors:

//document is an object represents webpage

// bgcolor is the Property of doc object

Example:

<!DOCTYPE html>

<html>

<title>Java-Script Functions...!!</title>

<script type="text/javascript">
function BgColorRed()

document.bgColor='red'

function BgColorBlue()

document.bgColor='blue'

function BgColorWhite()

document.bgColor='white'

</script>

</head>

<body>

<p>Click the following button to display Background Color..!!</p>

<input type="submit" onclick="BgColorRed()" value="RedBg"/>

<input type="submit" onclick="BgColorBlue()" value="BlueBg"/>

<input type="submit" onclick="BgColorWhite()" value="WhiteBg"/>

</body>

Self-Invoking Functions

Function expressions can be made "self-invoking". A self-invoking expression is invoked (started)


automatically, without being called. Function expressions will execute automatically if the
expression is followed by (). You cannot self-invoke a function declaration. You have to add
parentheses around the function to indicate that it is a function expression.

Example:

<!doctype html>
<body>

<p>Functions can be invoked automatically without being called:</p>

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

<script>

(function () {

document.getElementById("demo").innerHTML = "Hello! I Called MySelf";

})();

</script>

</body>

WORKING WITH JAVASCRIPT Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be
detected by JavaScript. Every element on a web page has certain events which can trigger a
JavaScript. Events are normally used in combination with functions.

EXAMPLES:

Clicking a button

A page is finished loading

An image is finished loading

Moving the mouse-cursor over an element

Entering an input field

Submitting a Form

A key Stroke .......!!

Events in JavaScript.

Event Description

click Occurs when the user clicks on a link or form element

error Occurs when an error happens during loading of doc

focus Occr when input focus is given to a form element.


load Occurs when a page is loaded into Navigator

mouseout Occurs when the user moves the pointer off

mouseover Occurs when the user moves the pointer over

reset when the user clears a form using the Reset button

select Occurs when the user selects a form element's field

submit Occurs when a form is submitted

unload Occurs when the user leaves a page

onClick: The onclick event occurs when the user clicks on an element.

Syntax

In HTML:

<element onclick="SomeJavaScriptCode">

In JavaScript:

object.onclick="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script>

function displayDate()

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

</script>

</head>
<body>

<p>Click the button to execute the <h3>displayDate()</h3></p>

<button id="myBtn" onclick="displayDate()">ClickMe</button>

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

</body>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

function MyMsg()

alert("Welcome to JSEvents");

</script>

</head>

<body>

<p>Click the button to display the alert Msg ..</p>

<button onclick="MyMsg()"><img src='html5.png' width=10px height=10px> </button>

<input type='submit' value="ClickMe" onclick="MyMsg()">

<input type='button' value="ClickMe" onclick="MyMsg()" >

</body>

ondblclick Event:

The ondblclick event occurs when the user double-clicks on an element.

Syntax:
In Html

<element ondblclick="SomeJavaScriptCode">

Syntax:

In JavaScript:

object.ondblclick="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script type='text/javascript'>

function MyColor()

document.getElementById("col").style.color="#FF0099";

</script>

</head>

<body>

<p id="col">Double Click the button to Chage the Color of the Text...!</p>

<button ondblclick="MyColor()">DClickMe</button>

</body>

Example:

<!doctype html>

<head>

<script>

function copyText()
{

document.getElementById("field2").value=document.getElementById("field1").value;

</script>

</head>

<body>

Field1: <input type="text" id="field1" value="Hello World!" /><br />

Field2: <input type="text" id="field2" />

<br /><br />

<button ondblclick="copyText()">Copy Text</button>

</body>

onload:

The onload event occurs when an object has been loaded. onload is most often used within the
<body> element to execute a script once a web page has completely loaded all content (including
images, script files, CSS files, etc.).

Syntax

In HTML:

<element onload="SomeJavaScriptCode">

In JavaScript:

object.onload="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script>
function load()

alert("Page is loaded");

</script>

</head>

<body onload="load()">

<h1>Hello World!</h1>

</body>

Example:

<!doctype html>

<head>

<script>

function loadImage()

alert("Image is loaded Successfully");

</script>

</head>

<body>

<img src="html5.png" onload="loadImage()" width="100" height="132" />

</body>

onunload Event:

The onunload event occurs once a page has unloaded (or the browser window has been closed).
onunload occurs when the user navigates away from the page (by clicking on a link, submitting a
form, closing the browser window, etc.)
Syntax

In HTML:

<element onunload="SomeJavaScriptCode">

In JavaScript:

object.onunload="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script>

function bye()

alert("Thank you for visiting MySite!!");

</script>

</head>

<body onunload="bye()">

<h1>Welcome to my World</h1>

<p>Close this window or press F5 to reload the page.</p>

</body>

onerror Event

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an
image).

Syntax
In HTML:

<element onerror="SomeJavaScriptCode">

In JavaScript:

object.onerror="SomeJavaScriptCode"

onerror is Supported by the Following HTML Tags:

<img>, <object>, <script>, <style>

Example:

<!doctype html>

<head>

<script>

function imgError()

alert('The image could not be loaded.');

</script>

</head>

<body>

<img src="water1.gif" onerror="imgError()">

<p> Image that does not exist, therefore the onerror event occurs.</p>

<p> If Image Existed NO Message displayed</p>

</body>

onmousemove Event:

The onmousemove event occurs when a user moves the mouse pointer over an element.
Syntax

In HTML:

<element onmousemove="SomeJavaScriptCode">

In JavaScript:

object.onmousemove="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script>

function bigImg(x)

x.style.height="84px";

x.style.width="84px";

function normalImg(x)

x.style.height="32px";

x.style.width="32px";

</script>

</head>

<body>

<img onmousemove="bigImg(this)" onmouseout="normalImg(this)" src="html.png" alt="Logo"


width="32" height="32" />

</body>
onmouseover and onmouseout:

These two event types will help you to create nice effects with images or even with text as well. The
onmouseover event occurs when you bring your mouse over any element and the onmouseout
occurs when you take your mouse out from that element.

Syntax

In HTML:

<element onmouseover="SomeJavaScriptCode">

In JavaScript:

object.onmouseover="SomeJavaScriptCode"

Syntax

In HTML:

<element onmouseout="SomeJavaScriptCode">

In JavaScript:

object.onmouseout="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script type="text/javascript">

function over()

alert("Mouse Over");

}
function out()

alert("Mouse Out");

</script>

</head>

<body>

<div onmouseover="over()" onmouseout="out()">

<h2> This is inside the division </h2>

</div>

</body>

Example:

<!doctype html>

<body>

<h1 onmouseover="style.color='red'"

onmouseout="style.color='black'">

Mouse over this text

</h1>

</body>

Example:

<!doctype html>

<body>

<a href="http://www.nareshit.com/"

onmouseover="document.bgColor='#FFFF00'"

onmouseout="document.bgColor='#FFFFEE'">
Move your mouse over me!

</a>

</body>

onresize Event

The onresize event occurs when the size of an element has changed.

Syntax

In HTML:

<element onresize="SomeJavaScriptCode">

In JavaScript:

object.onresize="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script>

function showMsg()

alert("Hi!! changed the size of the Browser Window!");

</script>

</head>

<body onresize="showMsg()">

<p>Try to resize the browser window.</p>

</body>
HTML onchange Event:

The onchange attribute fires the moment when the value of the element is changed. The onchange
attribute can be used with the <input>, <textarea>, and <select> elements.

Syntax

<element onchange="script">

Attribute Values

Value Description

script The script to be run on onchange

Example:

<!doctype html>

<head>

<script>

function checkField(val)

alert("The input value has changed. The new value is: " + val);

</script>

</head>

<body>

Enter text:

<input type="text" name="txt" value="NareshTech" onchange="checkField(this.value)">

<p>Modify the text in the input field, then click outside the field to fire onchange.</p>

</body>

HTML onselect Event


The onselect attribute fires after some text has been selected in an element. The onselect attribute
can be used within:

<input type="file">, <input type="password">,

<input type="text">, and <textarea>.

Syntax

<element onselect="script">

Attribute Values

Value Description

script The script to be run on onselect

Examples:

<!doctype html>

<head>

<script>

function showMsg()

alert("You have Selected My Text!");

</script>

</head>

<body>

Some text:

<input type="text" value="sraju!!" onselect="showMsg()">

</body>

</html>
Form Events:

onblur:The onblur event occurs when an object loses focus. Onblur is most often used with form
validation code (When the user leaves a form field).

Note: The onblur event is the opposite of the onfocus event.

Syntax

In HTML:

<element onblur="SomeJavaScriptCode">

In JavaScript:

object.onblur="SomeJavaScriptCode"

Supported JS objects:

Document, Window.

Example:

<!doctype html>

<head>

<script>

function upperCase()

var x=document.getElementById("fname");

x.value=x.value.toUpperCase();

function lowerCase()

var x=document.getElementById("fname");
x.value=x.value.toLowerCase();

</script>

</head>

<body>

Enter your name: <input type="text" id="fname" onblur="upperCase()" />

</body>

onfocus Event:

The onfocus event occurs when an element gets focus. Onfocus is most often used with <input>,
<select>, and <a>.

Note: The onfocus event is the opposite of the onblur event.

Syntax

In HTML:

<element onfocus="SomeJavaScriptCode">

In JavaScript:

object.onfocus="SomeJavaScriptCode"

Example:

<!doctype html>

<head>

<script type="text/javascript">

function setStyle(x)

document.getElementById(x).style.background="yellow";
}

</script>

</head>

<body>

<form action="html5.png" name="myform" id="form1">

<label>First name: </label> <br/>

<input type="text" id="fname" onfocus="setStyle(this.id)" />

<br />

<label>Last name: </label> <br/>

<input type="text" id="lname" onfocus="setStyle(this.id)" /> <br/>

<input type='submit' value="NextPage"/>

<input type='reset' value="Cancel"/>

</form>

</body>

HTML onsubmit Event :

The onsubmit attribute fires when a form is submitted. The onsubmit attribute is only used within:
<form>.

Syntax

<form onsubmit="script">

Attribute Values

Value Description

script The script to be run on onsubmit

Example:

<!doctype html>
<head>

<script>

function checkForm()

alert("The form is submitted");

</script>

</head>

<body>

<form action="nit.html" onsubmit="checkForm()">

First name: <input type="text" name="fname"><br>

Last name: <input type="text" name="lname"><br>

<input type="submit" value="Submit">

</body>

</html>

HTML onafterprint Event:

The onafterprint attribute fires after the user has set the page to print, and the print dialogue box
has appeared.

Syntax

<element onafterprint="script">

Attribute Values

Value Description

script The script to be run on onafterprint

Example:
<!doctype html>

<head>

<script>

function printmsg()

alert("This document is going to printed");

</script>

</head>

<body onafterprint="printmsg()">

<h1>Try to print this document</h1>

<p><b>Tip:</b> Keyboard shortcuts, such as Ctrl+P sets the page to print.</p>

</body>

HTML onbeforeprint Event Attribute:

The onbeforeprint attribute fires immediately after the user has set the page to print, but before the
print dialogue box appears.

Syntax

<element onbeforeprint="script">

Example:

<!doctype html>

<head>

<script>

function printmsg()

alert("You are now about to print this document!");


}

</script>

</head>

<body onbeforeprint="printmsg()">

<p>Keyboard shortcuts, such as Ctrl+P sets the page to print.</p>

</body>

Type Event Attribute

The type event attribute returns the type of the triggered event.

Syntax

event.type

Example:

<!doctype html>

<head>

<script>

function getEventType(event)

alert(event.type);

</script>

</head>

<body onmousedown="getEventType(event)">

<p>Click in the document. An alert box with type.!!</p>

</body>

JavaScript - Errors & Exceptions Handling


There are three types of errors in programming:

(a) Syntax Errors

(b) Runtime Errors

(c) Logical Errors:

Syntax errors:

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

Following example causes a syntax error because it is missing a closing parenthesis.

Example:

<!doctype html>

<head>

<script type="text/javascript">

window.document.write("Hey JS"

</script>

</head>

When a syntax error occurs in JavaScript, only the code contained within the same thread as the
syntax error is affected and code in other threads

Example:

<!doctype html>

<head>

<script type='text/javascript'>

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

document.write("Welcome to JS<br/>");
document.write("Thank U";

</script>

</head>

Logical Errors/Semantic Errors:

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

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

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x=100;

var y=10;

var z=x+y/2

document.write("The Value is: ",z)

</script>

</head>

The above script displays '105', to avoid invalid computations, we must use expression in a proper
format ie (x+y)/2.

Example:

<script type='text/javascript'>

var x=100;var y=10;


var z=(x+y)/2

document.write("The Value is: ",z)

</script>

Runtime errors:

Runtime errors, also called exceptions, occur during execution (after compilation/ interpretation).

The following example causes a run time error because here syntax is correct but at run time it is
trying to call a non existed method:

Example:

<!doctype html>

<head>

<script type="text/javascript">

document.write("Good One");

window.document.writepn("Hello");

</script>

</head>

What is Exception Handling?

An exception is a problem that arises during the execution of a program.

OR

Exception handling is the process of responding to the occurrence, during computation, of


exceptions.

The try...catch Statement:

The try...catch statement allows you to test a block of code for errors. The try block contains the
code to be run, and the catch block contains the code to be executed if an error occurs.
1 The try statement lets you test a block of code for errors.

2 The catch statement lets you handle the error.

3 The throw statement lets you create custom errors.

4 The finally statement lets you execute code, after try and catch, regardless of the result.

Syntax:

<script>

try

Code to run [break;]

catch ( e )

Code to run if an exception occurs [break;]

</script>

Examples:

<script>

try{

alrt("hi")

catch(e)

alert(e.description)

alert("hello")
</script>

JavaScript eval() Function

The eval() function evaluates or executes an argument.

Syntax

eval(expression)

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x=prompt("Enter value to evalu")

alert(eval(x))

alert("Next")

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

try

var x=prompt("Enter Any Value to Compute")

alert(eval(x))

}
catch(e)

alert("Sorry Alpha-Invalid: " +e.description)

alert("Next")

</script>

</head>

The finally Statement

The finally statement lets you execute code, after try and catch, regardless of the result:

Syntax:

try {

Block of code to try

catch(err) {

Block of code to handle errors

finally {

Block of code to be executed regardless of the try / catch result

Example:

<!doctype html>

<head>

<script type='text/javascript'>

try
{

var x=prompt("Enter Any Value to Compute")

alert(eval(x))

catch(e)

alert("Sorry Alpha-Invalid: " +e.description)

finally

alert("This Block Always Get Executed");

alert("Next")

</script>

</head>

The JS Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the
try...catch statement, you can control program flow and generate accurate error messages. The
exception can be a string, integer, Boolean or an object.

Syntax

throw exception

Example:

<!doctype html>

<body>

<script type="text/javascript">
var x=prompt("Enter Any Number: ","100")

try

if(x>100)

throw "Err1";

else if(x<=100)

throw "Err2";

else if(isNaN(x))

throw "Err3";

catch(err)

if(err=="Err1")

document.write("Error! The value is too high.");

if(err=="Err2")

document.write("Error! The value is too low.");

if(err=="Err3")
{

document.write("Error! The value is not a number.");

</script>

</body>

JavaScript Global Functions

JavaScript eval() Function

The eval() function evaluates or executes an argument.

Syntax

eval(expression)

Example:

<!doctype html>

<body>

<script type='text/javascript'>

eval("x=10;y=20;document.write(x*y)");

document.write("<br/>" + eval("2+2"));

document.write("<br/>" + eval(x+17));

</script>

</body>

JavaScript isFinite() function

The isFinite is used to determine whether a specified number is finite or not. isFinite is a top-level
function and is not associated with any object.
Syntax

isFinite(number)

Example

<!doctype html>

<body>

<script type='text/javascript'>

document.write(isFinite("Good Morning")+ "<br />");

document.write(isFinite(-9.34)+ "<br />");

document.write(isFinite("2009/01/01")+ "<br />");

document.write(isFinite(15-12)+ "<br />");

</script>

</body>

JavaScript : isNaN() function

The isNaN function is used to determine whether a value is "NaN" (not a number) or not. isNaN is a
top-level function and is not associated with any object.

Syntax

isNan(textvalue)

Example

<!doctype html>

<body>

<script type='text/javascript'>

document.write(isNaN("Good Morning")+ "<br />");

document.write(isNaN(-9.34)+ "<br />");

document.write(isNaN("2009/01/01")+ "<br />");


document.write(isNaN(15-12)+ "<br />");

</script>

</body>

JS parseInt and parseFloat:

To convert a string to a number, use the JavaScript functions

1. parseFloat (for conversion to a floating-point number) or

2. parseInt (for string-to-integer conversion).

JavaScript parseInt() Function:

The parseInt() function parses a string and returns an integer.

Syntax

parseInt(string)

Parameter Description

string Required. The string to be parsed

Example

<!doctype html>

<head>

<script type='text/javascript'>

var x="100";

var y="200";

var z=x+y;

alert("The sum(contanation) of the values are: " +z);


var xyz=parseInt(x)+parseInt(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

document.write(parseInt("10") + "<br />");

document.write(parseInt("10.33") + "<br />");

document.write(parseInt("34 45 66") + "<br />");

document.write(parseInt("He was 40") + "<br />");

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

document.write(parseInt("10",16)+ "<br />");

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x=prompt("Enter any value");

var y=prompt("Enter any value")

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseInt(x)+parseInt(y)
alert('Sum of the values are: ' +xyz)

</script>

</head>

JavaScript parseFloat() Function:

The parseFloat() function parses a string and returns a floating value.

Syntax

parseFloat(string)

Parameter Description

string Required. The string to be parsed

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x="100.25";

var y="200.25";

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseFloat(x)+parseFloat(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

Example:
<!doctype html>

<head>

<script type='text/javascript'>

document.write("<BR>" + parseInt("15"))

document.write("<BR>" + parseFloat("12.12345"))

document.write("<BR>" + parseInt("45.00000000"))

document.write("<BR>" + parseInt("23.348 44.218 55.405"))

document.write("<BR>" + parseFloat(" 55 aardvarks"))

document.write("<BR>" + parseFloat("Year 2002"))

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x=prompt("Enter any value");

var y=prompt("Enter any value")

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseFloat(x)+parseFloat(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>
The JS Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the
try...catch statement, you can control program flow and generate accurate error messages. The
exception can be a string, integer, Boolean or an object.

Syntax

throw exception

Example:

<!doctype html>

<body>

<script type="text/javascript">

var x=prompt("Enter Any Number: ","100")

try

if(x>100)

throw "Err1";

else if(x<=100)

throw "Err2";

else if(isNaN(x))

throw "Err3";

}
catch(err)

if(err=="Err1")

document.write("Error! The value is too high.");

if(err=="Err2")

document.write("Error! The value is too low.");

if(err=="Err3")

document.write("Error! The value is not a number.");

</script>

</body>

JavaScript Global Functions

JavaScript eval() Function

The eval() function evaluates or executes an argument.

Syntax

eval(expression)

Example:

<!doctype html>
<body>

<script type='text/javascript'>

eval("x=10;y=20;document.write(x*y)");

document.write("<br/>" + eval("2+2"));

document.write("<br/>" + eval(x+17));

</script>

</body>

JavaScript isFinite() function

The isFinite is used to determine whether a specified number is finite or not. isFinite is a top-level
function and is not associated with any object.

Syntax

isFinite(number)

Example

<!doctype html>

<body>

<script type='text/javascript'>

document.write(isFinite("Good Morning")+ "<br />");

document.write(isFinite(-9.34)+ "<br />");

document.write(isFinite("2009/01/01")+ "<br />");

document.write(isFinite(15-12)+ "<br />");

</script>

</body>

JavaScript : isNaN() function


The isNaN function is used to determine whether a value is "NaN" (not a number) or not. isNaN is a
top-level function and is not associated with any object.

Syntax

isNan(textvalue)

Example

<!doctype html>

<body>

<script type='text/javascript'>

document.write(isNaN("Good Morning")+ "<br />");

document.write(isNaN(-9.34)+ "<br />");

document.write(isNaN("2009/01/01")+ "<br />");

document.write(isNaN(15-12)+ "<br />");

</script>

</body>

JS parseInt and parseFloat:

To convert a string to a number, use the JavaScript functions

1. parseFloat (for conversion to a floating-point number) or

2. parseInt (for string-to-integer conversion).

JavaScript parseInt() Function:

The parseInt() function parses a string and returns an integer.

Syntax

parseInt(string)
Parameter Description

string Required. The string to be parsed

Example

<!doctype html>

<head>

<script type='text/javascript'>

var x="100";

var y="200";

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseInt(x)+parseInt(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

document.write(parseInt("10") + "<br />");

document.write(parseInt("10.33") + "<br />");

document.write(parseInt("34 45 66") + "<br />");

document.write(parseInt("He was 40") + "<br />");

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

document.write(parseInt("10",16)+ "<br />");


</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var x=prompt("Enter any value");

var y=prompt("Enter any value")

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseInt(x)+parseInt(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

JavaScript parseFloat() Function:

The parseFloat() function parses a string and returns a floating value.

Syntax

parseFloat(string)

Parameter Description

string Required. The string to be parsed

Example:

<!doctype html>
<head>

<script type='text/javascript'>

var x="100.25";

var y="200.25";

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseFloat(x)+parseFloat(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

document.write("<BR>" + parseInt("15"))

document.write("<BR>" + parseFloat("12.12345"))

document.write("<BR>" + parseInt("45.00000000"))

document.write("<BR>" + parseInt("23.348 44.218 55.405"))

document.write("<BR>" + parseFloat(" 55 aardvarks"))

document.write("<BR>" + parseFloat("Year 2002"))

</script>

</head>

Example:

<!doctype html>

<head>
<script type='text/javascript'>

var x=prompt("Enter any value");

var y=prompt("Enter any value")

var z=x+y;

alert("The sum(contanation) of the values are: " +z);

var xyz=parseFloat(x)+parseFloat(y)

alert('Sum of the values are: ' +xyz)

</script>

</head>

JavaScript Objects Introduction:

JavaScript is an Object Based Programming language. An Object Based Programming language allows
you to define your own objects and make your own variable types. An object has properties and
methods.

Properties: Properties are the values associated with an object.

Example:

length Width Height Name

Methods: Methods are the actions that can be performed on objects.

Open() Close() Resize()

Example:

<!doctype html>

<head>

<script type='text/javascript'>

person=new Object();

person.name='Ram';

person.age=30;
person.gender='male';

person.height=6;

document.write(person.name+' is '+person.age+' years old, '+person.gender+', and '+person.height+'


foot tall.');

</script>

</head>

NOTE:

In the above example object name repeated many times, to-overcome that drawback JS has 'with'
keyword..!!

with

There is a keyword associated with an object, which is 'with'. It creates a kind of halfway reference.
we can drop the repeated references to 'person', because with (person) has already made the
reference for us.

Syntax:

with (Object)

Statements;

Statements;

Statements;

Example:

<!doctype html>

<head>

<script type='text/javascript'>

person=new Object();
with (person)

name='Ram';

age=30;

gender='male';

height=6;

document.write(name+' is '+age+' years old, '+gender+', and '+height+' foot tall.');

</script>

</head>

JavaScript and HTML DOM:(Document Object Model)

1 JavaScript Objects:

2 Browser Objects

JavaScript Objects:

Array object Boolean object

Date object Math object

String object Number object RegExp object

Browser Objects:

Window object Navigator object

Screen object History object Location object

JavaScript Array

The Array object is used to store multiple values in a single variable


The following points should always be remembered when using arrays in JavaScript:

1. The array is a special type of variable.

2.Values are stored into an array by using the array name and by stating the location in the array you
wish to store the value in brackets.

Example: myArray[2] = "Hello World";

3. Values in an array are accessed by the array name and location of the value. Example: myArray[2];

4. JavaScript has built-in functions for arrays

Creating a JavaScript Array

Creating an array is slightly different from creating a normal variable. Because JavaScript has
variables and properties associated with arrays, you have to use a special function to create a new
array.

Create an Array

An array can be created in three ways.

1 Literal:

var myNames=[items];

2 Regular:

var myNames=new Array();

3 Condenced:

var myNames=new Array(items);

Example:

<!doctype html>

<head>

<script type='text/javascript'>

//Literal Way Array Declaration

var MyArr=['html5','css3','js','jQ','ajs'];

document.write("The Length of An Array is: " +MyArr.length);


document.write("<br>");

document.write("Number of Elements in an Array is: " +MyArr.length);

</script>

</head>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

function MyArrayLen()

//Literal Way Array Declaration with Function

var MyArr=['html5','css3','js','jQ','ajs'];

document.write("The Length of An Array is: " +MyArr.length);

document.write("<br>");

document.write("Number of Elements in an Array is: " +MyArr.length);

</script>

</head>

<body>

<p>Click the button to display the array Length ... </p>

<button onclick="MyArrayLen()"> Click_Array </button>

</body>

2: Regular:

var myNames=new Array();

myNames[0]="Ravi";
myNames[1]="Smith";

myNames[2]="Raju";

Example:

<!doctype html>

<head>

<script type='text/javascript'>

//Regular Way Array Declaration

var MyArr=new Array();

MyArr[0]='html5';

MyArr[1]='css3';

MyArr[2]='js';

MyArr[3]='jQ';

MyArr[4]='ajs';

MyArr[5]='ajs';

document.write("The Length of An Array is: " +MyArr.length);

document.write("<br>");

document.write("Number of Elements in an Array is: " +MyArr.length);

</script>

</head>

3: Condensed:

var myNames=new Array("Ravi","Smith","Raju");

Example:

<!doctype html>

<head>
<script type='text/javascript'>

//Condensed Way Array Declaration

var MyArr=new Array('html5','css3','js','jQ','ajs');

document.write("The Length of An Array is: " +MyArr.length);

document.write("<br>");

document.write("Number of Elements in an Array is: " +MyArr.length);

</script>

</head>

Array Methods and Properties

The Array object has predefined properties and methods:

var x=myNames.length // the number of elements in myNames

var y=myNames.indexOf("Raju") // the index position of "Raju"

Example:

<!doctype html>

<html>

<body>

<script>

var i;

var mynames = new Array();

mynames[0] = "Ravi";

mynames[1] = "sai";

mynames[2] = "Raju";

for (i=0;i<mynames.length;i++)

document.write(mynames[i] + "<br />");


}

</script>

</body>

Example:

<!doctype html>

<script>

var myArray = new Array();

myArray[0] = "Football";

myArray[1] = "Baseball";

myArray[2] = "Cricket";

document.write(myArray[0] + myArray[1] + myArray[2]);

</script>

JavaScript Array Sorting

Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser.
Well, this code has already been written and can be accessed by using the Array's sort method.

Example:

<script>

var x= new Array();

x[0] = "Football";

x[1] = "Baseball";

x[2] = "Cricket";

x.sort();

document.write(x[0] + x[1] + x[2]);

</script>
Example:

<!doctype html>

<script>

function myFunction()

var names = ["raju", "nit", "ramu", "scott"];

var x=document.getElementById("demo");

x.innerHTML=names.length;

</script>

<body>

<p id="demo">Click the button to create an array, then display it's length</p>

<button onclick="myFunction()">Length</button>

</body>

Example:

<!doctype html>

<body>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"];

function myFunction()

fruits.reverse();

var x=document.getElementById("demo");

x.innerHTML=fruits;

</script>
<p id="demo">Click the button to reverse the order of the elements in the array.</p>

<button onclick="myFunction()">Display</button>

</body>

JavaScript pop() Method:

The pop() method removes the last element of an array, and returns that element.

Note: This method changes the length of an array.

Note: To remove the first element of an array, use the shift() method.

Syntax: array.pop()

Example:

<!doctype html>

<head>

<script type='text/javascript'>

var techs = ["TeraData", "BigData", "Hadoop", "Spark"];

function myFunction()

techs.pop();

var x=document.getElementById("course");

x.innerHTML=techs;

</script>

<body>

<p id="course">Click the button to remove the last array element.</p>

<button onclick="myFunction()">Click_Tech</button>

</body>
Example:

<!doctype html>

<head>

<script type='text/javascript'>

arr=['smiley.jpg','fish.jpg','fish1.gif', 'nature.jpg', 'nature1.jpg', 'nature2.pg']

i=0;

function funpre()

i--

fun2()

function funnext()

i++

fun2()

function fun2()

document.getElementById('img1').src="img/"+arr[i]

</script>

</head>

<body>

<img id='img1' width='200px' height="200px" src='img/smiley.jpg'>

<br>

<input type='button' value='Next' onclick='funnext()'>


<input type='button' value='Previous' onclick='funpre()'>

</body>

Example:

<!doctype html>

<head>

<script type='text/javascript'>

arr=['fish.jpg','fish1.gif', 'nature.jpg', 'nature1.jpg','butterfly.gif',"bird.gif"]

i=0;

function fun1()

i++

if(i==6)

alert("No more images")

else

document.getElementById('img1').src="img/"+arr[i];

</script>

<body>

<img src="img/fish.jpg" width="300px" height="250px" id="img1">

<br>

<input type="button" value=" NEXT" onclick="fun1()">

</body>
JavaScript Timing Events

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing
events. It's very easy to time events in JavaScript. The two key methods that are used are:

1. setInterval() - executes a function, over and over again, at specified time intervals.

Syntax

window.setInterval("javascript function",milliseconds);

Example:

<!doctype html>

<head>

<script type='text/javascript'>

function myFunction()

setInterval(function(){alert("Hello")},3000);

</script>

</head>

<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Display</button>

</body>

2. setTimeout() - executes a function, once, after waiting a specified number of milliseconds

Syntax

window.setTimeout("javascript function",milliseconds);
Example:

<!doctype html>

<script type='text/javascript'>

function delayer()

window.location = "http://www.nareshit.com"

</script>

</head>

<body onLoad="setTimeout('delayer()', 5000)">

<h2>Prepare to be redirected!</h2>

<p>This page is a time delay redirect</p>

</body>

RealTime Example:

<!doctype html>

<head>

<script type='text/javascript'>

setInterval("fun1()",1000);

function fun1()

var dt=new Date

str=dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds()

document.getElementById('sp1').innerHTML=str

</script>
</head>

<body>

<span id="sp1" style="color:red;font-size:30"></span>

</body>

JavaScript String Object:

A JavaScript string stores a series of characters like "javascript". A string can be any text inside
double or single quotes:

Example:

var name = "javascript";

var name = 'javascript';

String indexes are zero-based: The first character is in position 0, the second in 1, and so on.

Syntax:

var str = new String("string");

OR

var txt = "string";

Properties:

1. length

Methods:

1. charAt()

2. match()

3. endsWith()

4. repeat()

5. big()
6. bold()

7. italics()

8. small()

9. fixed()

10. strike()

11. sub()

12. sup()

13. fontcolor()

14. fontsize()

15. blink() //depcrecated

16. link()

17. replace()

String Object Properties:

JavaScript length Property:

The length property returns the length of a string (in characters).

Syntax: string.length

Example:

<body>

<script>

var txt = "Naresh i Technologies!";

document.write(txt.length);

</script>

</body>
String Object Methods

JavaScript charAt() Method:

It returns the character at the specified index in a string. The index of the first character is 0, the
second character is 1, and so on.

Syntax: string.charAt(index)

Example:

<html>

<script>

function myFunction()

var str="Naresh i Technologies";

document.getElementById("demo").innerHTML=str.charAt(2);

</script>

<body>

<p id="demo">Click the button to display the third character of a string.</p>

<button onclick="myFunction()">Display_Character</button>

</body>

</html>

JS String Match:The match() method searches a string for a match against a regular expression, and
returns the matches, as an Array object

Note: This method returns null if no match is found.

Syntax: string.match()
Example:

<script>

var str="Java Script!";

document.write(str.match("Script") + "<br />");

document.write(str.match("java") + "<br />");

document.write(str.match("Scriptt") + "<br />");

document.write(str.match("Java!"));

</script>

JavaScript String endsWith() Method

The endsWith() method determines whether a string ends with the characters of a specified string.

This method returns true if the string ends with the characters, and false if not.

Note:

The endsWith() method is case sensitive.

Syntax

string.endsWith(searchvalue,length)

Parameter Values

Parameter Description

searchvalue Required. The string to search for

length Optional. Specify the length of the string to search. If omitted, the default value is
the length of the string

Example:

<head>
<script>

function myFunction()

var str = "Hello world, welcome to the universe.";

var n = str.endsWith("universe.");

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

</script>

</head>

<body>

<p id="demo">Click the button to check where if the string ends with the specified value.</p>

<button onclick="myFunction()">ClickMe </button>

</body>

JavaScript String repeat() method

The repeat() method returns a new string with a specified number of copies of the string it was
called on.

Syntax

string.repeat(count)

Parameter Values

Parameter Description

count Required. The number of times the original string value should be repeated
in the new string

Example:

<!doctype html>
<head>

<script type='text/javascript'>

var str="NareshiTechnologies<br/>";

document.write(str.repeat("6"));

</script>

</head>

Example:

<head>

<script>

function myFunction()

var str = "JavaScript!";

document.getElementById("demo").innerHTML = str.repeat(3);

</script>

</head>

<body>

<p>Click the button to display the extracted part of the string.</p>

<button onclick="myFunction()">RepeatString</button>

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

</body>

JS String Styles:

<script>

var txt = "Hello World!";


document.write("<p>Big: " + txt.big() + "</p>");

document.write("<p>Small: " + txt.small() + "</p>");

document.write("<p>Bold: " + txt.bold() + "</p>");

document.write("<p>Italic: " + txt.italics() + "</p>");

document.write("<p>Fixed: " + txt.fixed() + "</p>");

document.write("<p>Strike: " + txt.strike() + "</p>");

document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>");

document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>");

document.write("<p>Subscript: " + txt.sub() + "</p>");

document.write("<p>Superscript: " + txt.sup() + "</p>");

document.write("<p>Link: " + txt.link("http://www.nareshit.com") + "</p>");

document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");

</script>

String Replace

<script>

var str="Visit SunMicro!";

document.write(str.replace("SunMicro","NareshTech"));

</script>
JavaScript Math Object:

The Math object allows you to perform mathematical tasks. The Math object includes several
mathematical constants and methods.

Math Object Properties:

JavaScript PI Property

The PI property returns the ratio of a circle's area to the square of its radius, approximately 3.14

Syntax: Math.PI

Example:

<html>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Math.PI;

</script>

<body>

<p id="demo">Click the button to display PI.</p>

<button onclick="myFunction()">Display_PI</button>

</body>

</html>

Math Object Methods:

abs(x) Returns the absolute value of x

Syntax: Math.abs(x)
Example:

<html>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Math.abs(-7.25);

</script>

<body>

<p id="demo">Click the button to the absolute value of -7.25</p>

<button onclick="myFunction()">Absolute</button>

</body>

</html>

Example:

<html>

<script>

function myFunction()

var a=Math.abs(7.25);

var b=Math.abs(-7.25);

var c=Math.abs(null);

var d=Math.abs("Hello");

var e=Math.abs(2+3);

var x=document.getElementById("demo");

x.innerHTML=a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;

}
</script>

<body>

<p id="demo">Click the button to the absolute value of different numbers</p>

<button onclick="myFunction()">Absolute_Values</button>

</body>

</html>

EXAMPLE:

<script>

document.write(Math.round(0.60) + "<br />");

document.write(Math.round(0.50) + "<br />");

document.write(Math.round(0.49) + "<br />");

document.write(Math.round(-4.40) + "<br />");

document.write(Math.round(-4.60));

</script>

<script>

document.write(Math.max(5,10) + "<br />");

document.write(Math.max(0,150,30,20,38) + "<br />");

document.write(Math.max(-5,10) + "<br />");

document.write(Math.max(-5,-10) + "<br />");

document.write(Math.max(1.5,2.5));

</script>

JavaScript pow() Method

The pow() method returns the value of x to the power of y (xy).


Syntax: Math.pow(x,y)

Example:

<html>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Math.pow(4,3);

</script>

<body>

<p id="demo">Click the button to display the result of 4*4*4.</p>

<button onclick="myFunction()">Display_Result</button>

</body>

</html>

Example:

<html>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Math.sqrt(9);

</script>

<body>

<p id="demo">Click the button to display the square root of 9.</p>

<button onclick="myFunction()">Display_Square</button>
</body>

</html>

JavaScript Number Object

The Number object is an object wrapper for primitive numeric values. Number objects are created
with new Number().

Syntax: var num = new Number(value);

Number Object Properties

Property Description

MAX_VALUE Returns the largest number possible in JavaScript

MIN_VALUE Returns the smallest number possible in JS

NaN Represents a "Not-a-Number" value

Example:

<html>

<script>

function myFunction()

document.getElementById("demo").innerHTML=Number.MAX_VALUE;

</script>

<body>

<p id="demo">Click the button to display the largest possible number in JavaScript.</p>

<button onclick="myFunction()">Max_Value</button>

</body>

</html>
JavaScript RegExp Object

It is an object that describes a pattern of characters.When you search in a text, you can use a pattern
to describe what you are searching for. RE are used to perform powerful pattern-matching and
"search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

OR

Syntax:

var patt=/pattern/modifiers;

pattern ==> Specifies the pattern of an expression.

modifiers ==> Specify if a search should be global, case-sensitive, etc.

Brackets

Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character not between the brackets

[0-9] Find any digit from 0 to 9

[A-Z] Find any character from uppercase A to uppercase Z

[a-z] Find any character from lowercase a to lowercase z

[A-z] Find any character from uppercase A to lowercase z

Quantifiers

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more n's


n? Matches any string that contains zero or one n

n{X} Matches any string that contains a sequence of X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

Metacharacters

A metacharacter is simply an alphabetical character preceded by a backslash.

Character Description

. a single character

\s a whitespace character (space, tab, newline)

\S non-whitespace character

\d a digit (0-9)

\D a non-digit

\w a word character (a-z, A-Z, 0-9, _)

\W a non-word character

[aeiou] matches a single character in the given set

RegExp Object Properties

Property Description

global Specifies if the "g" modifier is set

ignoreCase Specifies if the "i" modifier is set

lastIndex The index at which to start the next match

multiline Specifies if the "m" modifier is set

source The text of the RegExp pattern

RegExp Object Methods

Method Description
compile() Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

JavaScript test() Method

It tests for a match in a string. This method returns true if it finds a match, otherwise it returns false.

Syntax: RegExpObject.test(string)

Parameter Description

string Required. The string to be searched

Example:

<!doctype html>

<head>

<script>

var patt1=new RegExp("h");

document.write(patt1.test("HTML5 is Next generation Web Platform..!!"));

</script>

</head>

The Browser Object Model (BOM)

Javascript Window Object:

The JavaScript Window Object is the highest level JavaScript object which corresponds to the web
browser window.

Methods
Window open() Method

It opens a new browser window.

Syntax

window.open(URL)

Example:

<!doctype html>

<body>

<form>

<input type="button" value="Click here to see" onclick="window.open('http://www.yahoo.com')"


/></form>

</body>

Example:

<html>

<head>

<script>

function myFunction()

window.open("http://www.google.com/");

window.open("http://www.nareshit.com/");

</script>

</head>

<body>

<p>Click the button to open multiple windows.</p>

<button onclick="myFunction()">Open Windows</button>


</body>

</html>

Window print() Method

The print() method prints the contents of the current window.

Syntax

window.print()

Example:

<head>

<script>

function myFunction()

window.print();

</script>

</head>

<body>

<p>Click the button to print the current page.</p>

<button onclick="myFunction()">Print this page</button>

</body>

Window stop() Method

The stop() method stops window loading.

Syntax
window.stop()

Example:

<head>

<script>

window.stop();

</script>

</head>

Window Object Properties

Window screenX and screenY Properties:

The screenX and screenY properties returns the x (horizontal) and y (vertical) coordinates of the
window relative to the screen

Syntax

window.screenX

window.screenY

Example:

<head>

<script type='text/javascript'>

document.write(window.screenX);

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

document.write(window.screenY);

</script>

</head>

Example:
<head>

<script>

function myFunction()

var myWindow = window.open("", "myWin");

myWindow.document.write("<br>ScreenX: " + myWindow.screenX);

myWindow.document.write("<br>ScreenY: " + myWindow.screenY + "</p>");

</script>

</head>

<body>

<button onclick="myFunction()">OpenWin</button>

</body>

Navigator Object

It contains information about the browser.

Navigator Object Properties

Property Description

appCodeName Returns the code name of the browser

appName Returns the name of the browser

appVersion Returns the version information of the browser

language Returns the language of the browser

Navigator appCodeName Property

The appCodeName property returns the code name of the browser.


Syntax

navigator.appCodeName

Note: All modern browsers returns "Mozilla", for compatibility reasons.

Note: This property is read-only.

Example:

<body>

<p id="demo">Click the button to display the code name of your browser.</p>

<button onclick="myFunction()">Display</button>

<script>

function myFunction()

var x = "Browser CodeName: " + navigator.appCodeName;

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

</script>

</body>

Navigator appName Property

It returns the name of the Web browser.

Syntax

navigator.appName

Note: This property is read-only.


Example:

<body>

<p id="demo">Click the button to display the name of your browser.</p>

<button onclick="myFunction()">Display</button>

<script>

function myFunction()

var x = "Browser CodeName: " + navigator.appName;

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

</script>

</body>

Examples:

<html>

<body>

<script type="text/javascript">

document.write("Version info: " + navigator.appVersion);

</script>

</body>

</html>

Example2:

<html>

<head>

<script>

function AllProperties()
{

document.write("<h1>");

document.write("Version info is: " + navigator.appVersion);

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

document.write("AppName is: " + navigator.appName);

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

document.write("appCodeName is: " + navigator.appCodeName);

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

document.write("cookieEnabled: " + navigator.cookieEnabled);

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

</script>

<head>

<body>

<p> Click to get Execute all Navigator Properties</p>

<input type='button' onclick='AllProperties()'

value="Display_Properties"/>

</body>

</html>

Navigator Object Methods

Method Description

javaEnabled() Specifies whether or not the browser has Java enabled

Example:

<html>

<body>
<script type="text/javascript">

document.write("Java enabled: " + navigator.javaEnabled());

</script>

</body>

</html>

JavaScript Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. The Navigator object
contains information about the visitor's browser name, version etc..

Example:

<body>

<div id="demo"></div>

<script type='text/javascript'>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";

txt+= "<p>Browser Name: " + navigator.appName + "</p>";

txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";

txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";

txt+= "<p>Browser Language: " + navigator.language + "</p>";

txt+= "<p>Browser Online: " + navigator.onLine + "</p>";

txt+= "<p>Platform: " + navigator.platform + "</p>";

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

</script>

</body>

Screen Object

It contains information about the visitor's screen.


Screen Object Properties

Property Description

availHeight Returns the height of screen(Excluding Windows Taskbar)

availWidth Returns the width of screen (Excluding Windows Taskbar)

height Returns the total height of the screen

width Returns the total width of the screen

Example:

<!doctype html>

<body>

<script type="text/javascript">

document.write("Total Width: " + screen.width +"<br/>");

document.write("Total Height: " + screen.height +"<br/>");

document.write("Total AWidth: " + screen.availWidth +"<br/>");

document.write("Total AHeight: " + screen.availHeight +"<br/>");

</script>

</body>

The History Object

It contains the URLs visited by the user . It is part of the window object and is accessed through the
window.history property.

History Object Properties

Property Description

length Returns the number of URLs in the history list

History Object Methods

Method Description
back() Loads the previous URL in the history list

forward() Loads the next URL in the history list

History length Property

The length property returns the number of URLs in the history list.

Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.

Syntax : history.length

Example:

<html>

<body>

<script type="text/javascript">

document.write("Number of URLs in history list: " + history.length);

</script>

</body>

</html>

History back() Method

The back() method loads the previous URL in the history list.

Syntax: history.back()

History forward() Method

The forward() method loads the Next URL in the history list.

Syntax: history.forward()
Example:

<html>

<head>

<script type="text/javascript">

function goBack()

window.history.back()

</script>

</head>

<body>

<input type="button" value="Back" onclick="goBack()" />

</body>

</html>

History go() Method

The go() method loads a specific URL from the history list.

Syntax

history.go(number|URL)

Parameter Values

Parameter Description

number|URL Required. The parameter can either be a number which goes to the URL
within the specific position (-1 goes back one page, 1 goes forward one page)

Example:

<head>
<script>

function goBack()

window.history.go(-2);

</script>

</head>

<body>

<p>Click the button to display the 2 Pages Backward History...</p>

<button onclick="goBack()">Go 2 pages back</button>

</body>

The History Object

It contains the URLs visited by the user . It is part of the window object and is accessed through the
window.history property.

History Object Properties

Property Description

length Returns the number of URLs in the history list

History Object Methods

Method Description

back() Loads the previous URL in the history list

forward() Loads the next URL in the history list

History length Property

The length property returns the number of URLs in the history list.

Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.
Syntax : history.length

Example:

<html>

<body>

<script type="text/javascript">

document.write("Number of URLs in history list: " + history.length);

</script>

</body>

</html>

History back() Method

The back() method loads the previous URL in the history list.

Syntax: history.back()

History forward() Method

The forward() method loads the Next URL in the history list.

Syntax: history.forward()

Example:

<html>

<head>

<script type="text/javascript">

function goBack()

{
window.history.back()

</script>

</head>

<body>

<input type="button" value="Back" onclick="goBack()" />

</body>

</html>

History go() Method

The go() method loads a specific URL from the history list.

Syntax

history.go(number|URL)

Parameter Values

Parameter Description

number|URL Required. The parameter can either be a number which goes to the URL
within the specific position (-1 goes back one page, 1 goes forward one page)

Example:

<head>

<script>

function goBack()

window.history.go(-2);

</script>

</head>
<body>

<p>Click the button to display the 2 Pages Backward History...</p>

<button onclick="goBack()">Go 2 pages back</button>

</body>

Location Object

The location object contains information about the current URL. The location object is part of the
window object and is accessed through the window.location property.

Location Object Properties

Property Description

hash Returns the anchor portion of a URL

host Returns the hostname and port of a URL

hostname Returns the hostname of a URL

href Returns the entire URL

Location href Property

The href property returns the entire URL of the current page.

Syntax: location.href

Example:

<html>

<body>

<script>

document.write(location.href);

</script>

</body>
</html>

Location Object Methods

Method Description

reload() Reloads the current document

replace() Replaces the current document with a new one

Location replace() Method:

The replace() method replaces the current document with a new one.

Syntax: location.replace(newURL)

Example:

<html>

<head>

<script>

function replaceDoc()

window.location.replace("http://www.nareshit.com")

</script>

</head>

<body>

<input type="button" value="Replace document" onclick="replaceDoc()" />

</body>

</html>

Document Object
Each HTML document loaded into a browser window becomes a Document object. It has the
following list of properties..!!

1 anchors 2 cookie 3 domain 4 forms

5 images 6 title 7 URL

Document title Property

The title property returns the title of the current document (the text inside the HTML title element).

Syntax

document.title

Example:

<!doctpe html>

<head>

<title>

Naresh i Technologies..!!

</title>

</head>

<body>

<script type='text/javascript'>

document.write(document.title)

</script>

</body>

Document Object:

Return the number of anchors in a document:

<html>
<body>

<a name="html">HTML Tutorial</a><br>

<a name="css">CSS Tutorial</a><br>

<a name="xml">XML Tutorial</a><br>

<a href="http://www.w3c.org">JavaScript Tutorial</a>

<p>Number of anchors:

<script>

document.write(document.anchors.length);

</script></p>

</body>

</html>

Return the number of forms in a document

<html>

<body>

<form name="Form1"></form>

<form name="Form2"></form>

<form></form>

<p>Number of forms:

<script>

document.write(document.forms.length);

</script></p>

</body>

</html>

Return the number of images in a document

<html>
<body>

<img border="0" src="html.png" width="150" height="113" />

<img border="0" src="html5.png" width="152" height="128" />

<p>Number of images:

<script>

document.write(document.images.length);

</script></p>

</body>

</html

Return the id of the first image in a document

<html>

<body>

<img id="html" border="0" src="html.png" width="150" height="113" />

<img id="html5" border="0" src="html5.png" width="152" height="128" />

<p>Id of first image:

<script>

document.write(document.images[0].id);

</script></p>

</body>

</html>

Return all name/value pairs of cookies in a document

<html>

<body>

Cookies associated with this document:

<script>
document.write(document.cookie);

</script>

</body>

</html>

Return the title of a document:

<html>

<head>

<title>My title</title>

</head>

<body>

The title of the document is:

<script>

document.write(document.title);

</script>

</body>

</html>

Return Full URL:

<html>

<body>

The full URL of this document is:

<script>

document.write(document.URL);

</script>

</body>

</html>
<head>

<title>My WebPage</title>

</head>

<body>

The title of the document is:

<script type='text/javascript'>

document.write(document.title);

</script>

</body>

</html>

Container Tags :

Elements can hold other html Elements/Controls.

Example:

<div>,<p>,<table>,<span>...!

Non-Containesr Tags:

Element Can hold only text can not hold Html Controls/Elements.

Example:

<Textbox>,<Button>,<Radio>,<Textarea>

InnerHTML In JavaScript:

The innerHTML property is used along with getElementById within your JavaScript code to refer to
an HTML element and change its contents.
Syntax

document.getElementById('{ID of element}').innerHTML = '{content}';

Note:

All Paired tags are not containers, but all container tags are paired tags.

Example

<head>

<script type='text/javascript'>

function MyFun()

var val=document.getElementById("t1").value;

alert(val);

</script>

</head>

<body>

User Name: <br/>

<input type="text" name='uname' id='t1'>

<br/>

<input type="button" value="Click" onclick="MyFun()">

</body>

Example:

<head>

<script type='text/javascript'>

function fun1()
{

alert(document.getElementById('txtarea1').value);

alert(document.getElementById('p1').innerHTML);

</script>

</head>

<body>

<p id='p1'><img src='fish1.gif' width=100px heght=60px></p>

<textarea id='txtarea1'></textarea>

<br/>

<input type="button" value="Click" onclick="fun1()">

</body>

JavaScript Use Strict

"use strict"; Defines that JavaScript code should be executed in "strict mode". The "use strict"
directive is new in JavaScript 1.8.5 (ECMAScript version 5).

Declaring Strict Mode

Declared at the beginning of a JavaScript file, it has global scope (all code will execute in strict
mode):

Example:

<body>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>

"use strict";

x = 3.14; // This will cause an error (x is not defined).

</script>

</body>
Why Strict Mode?

Strict mode makes it easier to write "secure" JavaScript. Strict mode changes previously accepted
"bad syntax" into real errors.

What is a Webform?

A Webform (HTML form) allows a user to enter data that is sent to a server for processing. These
forms contains checkboxes, radio buttons, or text fields. Webforms are defined in formal
programming languages such as HTML, Perl, Php, Java or .NET.

JavaScript Form Validation:

HTML form validation can be done by a JavaScript. JavaScript, provides a way to validate form's data
on the client's computer before sending it to the web server. Form validation generally performs two
functions.

Basic Validation - The form must be checked to make sure data was entered into each form field that
required it. This would need just loop through each field in the form and check for data.

Data Format Validation - The data that is entered must be checked for correct form and value. This
would need to put more logic to test correctness of data.

Data Validation

It is the process of ensuring that computer input is clean, correct, and useful.

1 The purpose of data validation is to ensure correct input to a computer application.

2 Validation can be defined by many different methods, and deployed in many different ways.

3 Server side validation is performed by a web server, after input has been sent to the server.

4 Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

Constraint validation HTML Input Attributes

Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

Form data that typically are checked by a JavaScript:

1. If a text input is empty or not

2. If a text input is all numbers

3. If a text input is all letters (only Alphabets)

4. has the user left required fields empty?

5. has the user entered a valid e-mail address?

6. If a text input is all alphanumeric characters (numbers & letters)

7. If a text input has the correct number of characters in it

8. If a selection has been made from an HTML select

9. has the user entered a valid date?

10. has the user entered text in a numeric field?


Example:

<!doctype html>

<head>

<script type='text/javascript'>

function notEmpty()

var myTextField = document.getElementById('myText');

if(myTextField.value != "")

alert("You entered: " + myTextField.value)

else

alert("Would you please enter some text?")

</script>

</head>

<body>

<form action='nit.html'>

<input type='text' id='myText' /><br/>

<input type='button' onclick='notEmpty()' value='Form Validate' />

</form>

</body>

What is a Webform?

A Webform (HTML form) allows a user to enter data that is sent to a server for processing. These
forms contains checkboxes, radio buttons, or text fields. Webforms are defined in formal
programming languages such as HTML, Perl, Php, Java or .NET.
JavaScript Form Validation:

HTML form validation can be done by a JavaScript. JavaScript, provides a way to validate form's data
on the client's computer before sending it to the web server. Form validation generally performs two
functions.

Basic Validation - The form must be checked to make sure data was entered into each form field that
required it. This would need just loop through each field in the form and check for data.

Data Format Validation - The data that is entered must be checked for correct form and value. This
would need to put more logic to test correctness of data.

Data Validation

It is the process of ensuring that computer input is clean, correct, and useful.

1 The purpose of data validation is to ensure correct input to a computer application.

2 Validation can be defined by many different methods, and deployed in many different ways.

3 Server side validation is performed by a web server, after input has been sent to the server.

4 Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

Constraint validation HTML Input Attributes

Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description
disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

Form data that typically are checked by a JavaScript:

1. If a text input is empty or not

2. If a text input is all numbers

3. If a text input is all letters (only Alphabets)

4. has the user left required fields empty?

5. has the user entered a valid e-mail address?

6. If a text input is all alphanumeric characters (numbers & letters)

7. If a text input has the correct number of characters in it

8. If a selection has been made from an HTML select

9. has the user entered a valid date?

10. has the user entered text in a numeric field?

Example:

<!doctype html>

<head>

<script type='text/javascript'>

function notEmpty()

var myTextField = document.getElementById('myText');

if(myTextField.value != "")
{

alert("You entered: " + myTextField.value)

else

alert("Would you please enter some text?")

</script>

</head>

<body>

<form action='nit.html'>

<input type='text' id='myText' /><br/>

<input type='button' onclick='notEmpty()' value='Form Validate' />

</form>

</body>

Automatic HTML Form Validation

Example:

<!doctype html>

<body>

<form action="nit.html" method="post">

<input type="text" name="fname" required>

<input type="submit" value="Submit">

</form>

<p>If you click submit, without filling out the text field, your browser will display an error
message.</p>

</body>
The disabled Attribute

The disabled attribute specifies that the input field is disabled. A disabled element is un-usable and
un-clickable. Disabled elements will not be submitted.

Example:

<!doctype html>

<body>

<form action="nit.html">

First name:<br>

<input type="text" name="firstname" value ="John" disabled><br>

Last name:<br>

<input type="text" name="lastname"><br/>

<input type='submit' value="Disabled">

</form>

</body>

Disable Button

<!doctype html>

<head>

<script>

function disableElement()

document.getElementById("secondbtn").disabled=true;

</script>

</head>

<body>
<form>

Buttons:<br/>

<input type="button" id="firstbtn" value="OK">

<input type="button" id="secondbtn" value="Cancel">

<button onclick="disableElement()">Disable button</button>

</form>

</body>

Return the Value of button:

<!doctype html>

<body>

<input type="button" id="button1" value="Click Me!">

<p>The text on the button is:

<script>

document.write(document.getElementById("button1").value);

</script></p>

</body>

Close the new window

<!doctype html>

<head>

<script>

var myWindow;

function openWin()

myWindow = window.open("", "", "width=400, height=200");

}
function closeWin()

myWindow.close();

</script>

</head>

<body>

<input type="button" value="Open 'myWindow'" onclick="openWin()" />

<input type="button" value="Close 'myWindow'" onclick="closeWin()" />

</body>

VALIDATING RADIO BUTTONS

<!doctype html>

<head>

<script type="text/javascript">

function validate()

var r1 = document.getElementById('male').checked;

var r2 = document.getElementById('female').checked;

if((r1=="") && (r2=="")){

alert("Select either Male or Female");

return false;

return true;

</script>

</head>
<body>

You are?

<form name="form1" method="post" action='nit.html'>

<input type="radio" id="male" value="male">Male

<input type="radio" id="female" value="female">Female

<input type="submit" onclick="return validate();" value='Submit'>

</form>

</body>

Email Validation:

We can validate email address at client side and server side. To validate email address on client side,
we can use java script with regular expression. Java script can check the regular expression pattern
for valid email address. We have different regular expression patterns for validating email address.

Every email is made up for 5 parts:

1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores

2. The at symbol @

3. A combination of letters, numbers, hyphens, and/or periods

4. A period

5. The top level domain (com, net, org, us, gov, ...)

Valid Examples:

[email protected]

Example: (Login Validations as Per Live Project Resqs.)

<head>

<script type='text/javascript'>

function LoginValidate()
{

if(document.getElementById('un').value.length>=6

&&

document.getElementById('pw').value.length>=6)

document.getElementById('but1').disabled=false

else

document.getElementById('but1').disabled=true

</script>

</head>

<body>

<input type='text' id='un' onblur='LoginValidate()'>

<br>

<input type='password' id='pw' onblur='LoginValidate()'>

<br/>

<input type="button" value="Click" id="but1" disabled>

</body>

---------------------------------------------------------------------END-----------------------------------------------------------
------------

You might also like