Complete JavaScript
Complete JavaScript
It is loosely or weakly typed or light weight programming. Scripts are becoming more popular due to
the emergence of web-based applications.
1. Because of code executes on the users computer, in some cases it can be exploited for malicious
purposes. (Security Issues)
Types of 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
7. Dart (Google)
8. Brython
The Script which is running within the web server is called as server side scripting.
Example:
Features of JavaScript
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.”
"Lightweight Editors" are not as powerful as IDEs, but they’re fast, elegant and simple.
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:
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>
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/>");
</script>
</head>
Example:
<!doctype html>
<head>
<script>
document.write("<br/>");
</script>
</head>
Example:
<!doctype html>
<head>
<script>
document.write("<br/>");
</script>
</head>
Example:
<!doctype html>
<head>
<script>
window.document.write("Welcome to JavaScript")
document.write("<br>")
document.write("Good Bye...!!")
</script>
</head>
Syntax
document.write(exp1,exp2,exp3,...)
Example:
<!doctype html>
<body>
<script type='text/javascript'>
</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!");
</script>
</pre>
<pre>
<script type='text/javascript'>
document.writeln("Hello World!");
</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'>
</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>");
</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.
2. Multiline 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>
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
JavaScript Literals
10.50; 1001
Example:
<!DOCTYPE html>
<body>
<script>
var a=10
var a=9.99
</script>
</body>
"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;
</script>
</body>
Programmers have used different ways of joining multiple words into one variable name:
Hyphens:
Underscore:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
Example:
<!doctype html>
<script>
var1 = 10
var2 = 20
</script>
Example:
<!doctype html>
<script>
</script>
Example:
<!DOCTYPE html>
<body>
<script>
</script>
</body>
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";
</script>
</body>
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 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:
NOTE:
To use an external script, point to the .js file in the "src" attribute of the <script> tag:
document.write("<b>Bye...!!");
<html>
<head>
</head>
<body>
</body>
</html>
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>
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 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>
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>
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()
{
</script>
</head>
<body>
</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)
else
</script>
<body>
</body>
Example:
<html>
<head>
<script type="text/javascript">
function show_confirm()
if (r==true)
else
</script>
</head>
<body>
</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">
</head>
<body>
</body>
</html>
Example2:
<html>
<head>
<script type="text/javascript">
function show_prompt()
</script>
</head>
<body>
</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.
3 Names can also begin with $ and _ (but we will not use it in this tutorial)
var x = 10;
var _value="NareshIT";
var 1abc=30;
var *a=320;
Example:
<!doctype html>
<head>
<script>
var x = 10;
var y = 20;
var z=x+y;
</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>
document.write(bname +"<br>")
document.write(price +"<br>")
</script>
</body>
Value = undefined
Example:
<!DOCTYPE html>
<body>
<h2>JavaScript Variables</h2>
<script>
var bname;
document.write(bname)
</script>
</body>
Re-Declaring JavaScript Variables
Example:
<!DOCTYPE html>
<body>
<h2>JavaScript Variables</h2>
<p id="txt"></p>
<script>
var bname;
document.getElementById("txt").innerHTML = bname;
</script>
</body>
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>
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 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.
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;
}
Example:
<!doctype html>
<head>
<script>
var x = 5;
document.write(x)
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;
Example:
<head>
<script>
let x = 5;
document.write(x)
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>
<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.
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
document.write(name + "<br>");
document.write(age + "<br>");
document.write(isStudent + "<br>");
// Declaring constant
const PI = 3.14;
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>
<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.
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
document.write(name + "<br>");
document.write(age + "<br>");
document.write(isStudent + "<br>");
// Declaring constant
const PI = 3.14;
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>
<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 provides different data types to hold different types of values. There are two types of data
types in JavaScript.
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:
JavaScript has five primitive data types. These are the most simple forms of data we can use in JS
programming.
Data Type Description
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("<br/>")
</script>
</head>
Example:
<!doctype html>
<head>
<script type="text/javascript">
Str1="Hello",var Str2='World'
document.write("<br/>")
</script>
</head>
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
Example
Example:
<!doctype html>
<head>
<script type="text/javascript">
document.write("<br>");
document.write("<br>");
</script>
</head>
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.
Example:
<!doctype html>
<head>
<script type="text/javascript">
document.write("<br>");
</script>
</head>
Undefined
Example:
<!doctype html>
<head>
<script type="text/javascript">
var x;
var y;
</script>
</head>
null:
Example:
Example:
<!doctype html>
<head>
<script type="text/javascript">
var x=null;
var y=null;
document.write("The value is: "+y);
</script>
</head>
Object:
Declaring Variables as Objects.When a variable is declared with the keyword "new", the variable is
declared as an object:
Syntax:
Dynamic Types:
JavaScript has dynamic types. This means that the same variable can be used as different types:
Example
Example:
<!doctype html>
<body>
<script>
var x;
document.write(x +"<br/>");
var x=96;
document.write(x);
document.write("<br/>");
document.write(x +"<br/>");
var x=null;
document.write(x +"<br/>");
var x=true;
document.write(x +"<br/>");
</script>
</body>
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>
</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
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
<!DOCTYPE html>
<body>
<script>
var x = 10;
var y = 4;
document.write("<br>");
document.write("<br>");
document.write("<br>");
document.write("<br>");
</script>
</body>
Example:
<!DOCTYPE html>
<body>
<script>
x = 10;
x = 20;
x += 30;
x = 50;
x -= 20;
x = 5;
x *= 25;
document.write(x + "<br>"); // Prints: 125
x = 50;
x /= 10;
x = 100;
x %= 15;
document.write(x); // Prints: 10
</script>
</body>
There are two operators which can also used be for strings.
Example:
<!DOCTYPE html>
<body>
<script>
str1 += str2;
document.write(str1); // Outputs: Hello World!
</script>
</body>
Example:
<!DOCTYPE html>
<body>
<script>
x = 10;
document.write(++x); // Prints: 11
x = 10;
document.write(x++); // Prints: 10
x = 10;
document.write(--x); // Prints: 9
document.write("<p>" + x + "</p>"); // Prints: 9
x = 10;
document.write(x--); // Prints: 10
</script>
</body>
3 do/while - also loops through a block of code while a specified condition is true
for Loop
A for loop enables a particular set of conditions to be executed repeatedly until a condition is
satisfied.
Syntax:
Example:
<!doctype html>
<body>
<script type="text/javascript">
for (i=1;i<=5;i++)
document.write("<br />");
</script>
</body>
Example:
<!doctype html>
<body>
<script type="text/javascript">
document.write("</h" + i + ">");
</script>
</body>
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("<br />");
i++;
</script>
</body>
Example:
<!doctype html>
<head>
<script>
counter=0
++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
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++;
</script>
</head>
Example:
<!doctype html>
<head>
<script>
count = 1
do
</script>
</head>
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("<br />");
</script>
</body>
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("<br />");
</script>
</body>
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:
Example: For In
<!doctype html>
<body>
<script type="text/javascript">
var pros;
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">
//Declaring Arguments
window.alert("Welcome to Functions...!!")
alert("FunctionsAreCodeReusability...!!")
</script>
</head>
<body>
<button onclick="WishMe()">ClickHere.!</button>
</body>
Example:
<!doctype html>
<head>
<script type="text/javascript">
function popup()
alert("Hello World")
</script>
</head>
<body>
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 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()
</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>
</script>
Example:
<!doctype html>
<head>
<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>
<script type="text/javascript">
function myFunction(name,job)
</script>
</head>
<body>
</body>
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()
var a=10,b=20
</script>
</head>
<body>
<button onclick="Display1()">HiTMe</button>
</body>
</html>
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()
var a=10,b=20
function Display2()
var a=10
</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 ();
</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("<br/>");
local_global_variable();
</script>
</body>
BackGround Colors:
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>
</body>
Self-Invoking Functions
Example:
<!doctype html>
<body>
<p id="demo"></p>
<script>
(function () {
})();
</script>
</body>
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
Submitting a Form
Events in JavaScript.
Event Description
reset when the user clears a form using the Reset button
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 id="demo"></p>
</body>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
function MyMsg()
alert("Welcome to JSEvents");
</script>
</head>
<body>
</body>
ondblclick Event:
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>
</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()
</script>
</head>
<body>
</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()
</script>
</head>
<body onunload="bye()">
<h1>Welcome to my World</h1>
</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"
Example:
<!doctype html>
<head>
<script>
function imgError()
</script>
</head>
<body>
<p> Image that does not exist, therefore the onerror event occurs.</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>
</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>
</body>
Example:
<!doctype html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
</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()
</script>
</head>
<body onresize="showMsg()">
</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
Example:
<!doctype html>
<head>
<script>
function checkField(val)
alert("The input value has changed. The new value is: " + val);
</script>
</head>
<body>
Enter text:
<p>Modify the text in the input field, then click outside the field to fire onchange.</p>
</body>
Syntax
<element onselect="script">
Attribute Values
Value Description
Examples:
<!doctype html>
<head>
<script>
function showMsg()
</script>
</head>
<body>
Some text:
</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).
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>
</body>
onfocus Event:
The onfocus event occurs when an element gets focus. Onfocus is most often used with <input>,
<select>, and <a>.
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>
<br />
</form>
</body>
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
Example:
<!doctype html>
<head>
<script>
function checkForm()
</script>
</head>
<body>
</body>
</html>
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
Example:
<!doctype html>
<head>
<script>
function printmsg()
</script>
</head>
<body onafterprint="printmsg()">
</body>
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()
</script>
</head>
<body onbeforeprint="printmsg()">
</body>
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)">
</body>
Syntax errors:
Syntax errors, also called parsing errors, occur at compile time for traditional programming
languages, at interpret time for JavaScript.
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 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
</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'>
</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>
OR
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.
4 The finally statement lets you execute code, after try and catch, regardless of the result.
Syntax:
<script>
try
catch ( e )
</script>
Examples:
<script>
try{
alrt("hi")
catch(e)
alert(e.description)
alert("hello")
</script>
Syntax
eval(expression)
Example:
<!doctype html>
<head>
<script type='text/javascript'>
alert(eval(x))
alert("Next")
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
try
alert(eval(x))
}
catch(e)
alert("Next")
</script>
</head>
The finally statement lets you execute code, after try and catch, regardless of the result:
Syntax:
try {
catch(err) {
finally {
Example:
<!doctype html>
<head>
<script type='text/javascript'>
try
{
alert(eval(x))
catch(e)
finally
alert("Next")
</script>
</head>
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")
if(err=="Err2")
if(err=="Err3")
{
</script>
</body>
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>
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'>
</script>
</body>
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'>
</script>
</body>
Syntax
parseInt(string)
Parameter Description
Example
<!doctype html>
<head>
<script type='text/javascript'>
var x="100";
var y="200";
var z=x+y;
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
document.write("<br />");
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var z=x+y;
var xyz=parseInt(x)+parseInt(y)
alert('Sum of the values are: ' +xyz)
</script>
</head>
Syntax
parseFloat(string)
Parameter Description
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var x="100.25";
var y="200.25";
var z=x+y;
var xyz=parseFloat(x)+parseFloat(y)
</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"))
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var z=x+y;
var xyz=parseFloat(x)+parseFloat(y)
</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">
try
if(x>100)
throw "Err1";
else if(x<=100)
throw "Err2";
else if(isNaN(x))
throw "Err3";
}
catch(err)
if(err=="Err1")
if(err=="Err2")
if(err=="Err3")
</script>
</body>
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>
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'>
</script>
</body>
Syntax
isNan(textvalue)
Example
<!doctype html>
<body>
<script type='text/javascript'>
</script>
</body>
Syntax
parseInt(string)
Parameter Description
Example
<!doctype html>
<head>
<script type='text/javascript'>
var x="100";
var y="200";
var z=x+y;
var xyz=parseInt(x)+parseInt(y)
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
document.write("<br />");
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var z=x+y;
var xyz=parseInt(x)+parseInt(y)
</script>
</head>
Syntax
parseFloat(string)
Parameter Description
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var x="100.25";
var y="200.25";
var z=x+y;
var xyz=parseFloat(x)+parseFloat(y)
</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"))
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var z=x+y;
var xyz=parseFloat(x)+parseFloat(y)
</script>
</head>
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.
Example:
Example:
<!doctype html>
<head>
<script type='text/javascript'>
person=new Object();
person.name='Ram';
person.age=30;
person.gender='male';
person.height=6;
</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;
</script>
</head>
1 JavaScript Objects:
2 Browser Objects
JavaScript Objects:
Browser Objects:
JavaScript Array
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.
3. Values in an array are accessed by the array name and location of the value. Example: myArray[2];
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
1 Literal:
var myNames=[items];
2 Regular:
3 Condenced:
Example:
<!doctype html>
<head>
<script type='text/javascript'>
var MyArr=['html5','css3','js','jQ','ajs'];
</script>
</head>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
function MyArrayLen()
var MyArr=['html5','css3','js','jQ','ajs'];
document.write("<br>");
</script>
</head>
<body>
</body>
2: Regular:
myNames[0]="Ravi";
myNames[1]="Smith";
myNames[2]="Raju";
Example:
<!doctype html>
<head>
<script type='text/javascript'>
MyArr[0]='html5';
MyArr[1]='css3';
MyArr[2]='js';
MyArr[3]='jQ';
MyArr[4]='ajs';
MyArr[5]='ajs';
document.write("<br>");
</script>
</head>
3: Condensed:
Example:
<!doctype html>
<head>
<script type='text/javascript'>
document.write("<br>");
</script>
</head>
Example:
<!doctype html>
<html>
<body>
<script>
var i;
mynames[0] = "Ravi";
mynames[1] = "sai";
mynames[2] = "Raju";
for (i=0;i<mynames.length;i++)
</script>
</body>
Example:
<!doctype html>
<script>
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
</script>
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>
x[0] = "Football";
x[1] = "Baseball";
x[2] = "Cricket";
x.sort();
</script>
Example:
<!doctype html>
<script>
function myFunction()
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>
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>
The pop() method removes the last element of an array, and returns that element.
Note: To remove the first element of an array, use the shift() method.
Syntax: array.pop()
Example:
<!doctype html>
<head>
<script type='text/javascript'>
function myFunction()
techs.pop();
var x=document.getElementById("course");
x.innerHTML=techs;
</script>
<body>
<button onclick="myFunction()">Click_Tech</button>
</body>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
i=0;
function funpre()
i--
fun2()
function funnext()
i++
fun2()
function fun2()
document.getElementById('img1').src="img/"+arr[i]
</script>
</head>
<body>
<br>
</body>
Example:
<!doctype html>
<head>
<script type='text/javascript'>
i=0;
function fun1()
i++
if(i==6)
else
document.getElementById('img1').src="img/"+arr[i];
</script>
<body>
<br>
</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>
<button onclick="myFunction()">Display</button>
</body>
Syntax
window.setTimeout("javascript function",milliseconds);
Example:
<!doctype html>
<script type='text/javascript'>
function delayer()
window.location = "http://www.nareshit.com"
</script>
</head>
<h2>Prepare to be redirected!</h2>
</body>
RealTime Example:
<!doctype html>
<head>
<script type='text/javascript'>
setInterval("fun1()",1000);
function fun1()
str=dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds()
document.getElementById('sp1').innerHTML=str
</script>
</head>
<body>
</body>
A JavaScript string stores a series of characters like "javascript". A string can be any text inside
double or single quotes:
Example:
String indexes are zero-based: The first character is in position 0, the second in 1, and so on.
Syntax:
OR
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()
16. link()
17. replace()
Syntax: string.length
Example:
<body>
<script>
document.write(txt.length);
</script>
</body>
String Object Methods
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()
document.getElementById("demo").innerHTML=str.charAt(2);
</script>
<body>
<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
Syntax: string.match()
Example:
<script>
document.write(str.match("Java!"));
</script>
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:
Syntax
string.endsWith(searchvalue,length)
Parameter Values
Parameter Description
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 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>
</body>
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()
document.getElementById("demo").innerHTML = str.repeat(3);
</script>
</head>
<body>
<button onclick="myFunction()">RepeatString</button>
<p id="demo"></p>
</body>
JS String Styles:
<script>
document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");
</script>
String Replace
<script>
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.
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>
<button onclick="myFunction()">Display_PI</button>
</body>
</html>
Syntax: Math.abs(x)
Example:
<html>
<script>
function myFunction()
document.getElementById("demo").innerHTML=Math.abs(-7.25);
</script>
<body>
<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");
}
</script>
<body>
<button onclick="myFunction()">Absolute_Values</button>
</body>
</html>
EXAMPLE:
<script>
document.write(Math.round(-4.60));
</script>
<script>
document.write(Math.max(1.5,2.5));
</script>
Example:
<html>
<script>
function myFunction()
document.getElementById("demo").innerHTML=Math.pow(4,3);
</script>
<body>
<button onclick="myFunction()">Display_Result</button>
</body>
</html>
Example:
<html>
<script>
function myFunction()
document.getElementById("demo").innerHTML=Math.sqrt(9);
</script>
<body>
<button onclick="myFunction()">Display_Square</button>
</body>
</html>
The Number object is an object wrapper for primitive numeric values. Number objects are created
with new Number().
Property Description
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
OR
Syntax:
var patt=/pattern/modifiers;
Brackets
Expression Description
Quantifiers
Quantifier Description
Metacharacters
Character Description
. a single character
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\W a non-word character
Property Description
Method Description
compile() Compiles a regular expression
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
Example:
<!doctype html>
<head>
<script>
</script>
</head>
The JavaScript Window Object is the highest level JavaScript object which corresponds to the web
browser window.
Methods
Window open() Method
Syntax
window.open(URL)
Example:
<!doctype html>
<body>
<form>
</body>
Example:
<html>
<head>
<script>
function myFunction()
window.open("http://www.google.com/");
window.open("http://www.nareshit.com/");
</script>
</head>
<body>
</html>
Syntax
window.print()
Example:
<head>
<script>
function myFunction()
window.print();
</script>
</head>
<body>
</body>
Syntax
window.stop()
Example:
<head>
<script>
window.stop();
</script>
</head>
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()
</script>
</head>
<body>
<button onclick="myFunction()">OpenWin</button>
</body>
Navigator Object
Property Description
navigator.appCodeName
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()
document.getElementById("demo").innerHTML = x;
</script>
</body>
Syntax
navigator.appName
<body>
<button onclick="myFunction()">Display</button>
<script>
function myFunction()
document.getElementById("demo").innerHTML = x;
</script>
</body>
Examples:
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Example2:
<html>
<head>
<script>
function AllProperties()
{
document.write("<h1>");
document.write("<br/>");
document.write("<br/>");
document.write("<br/>");
document.write("</h1>");
</script>
<head>
<body>
value="Display_Properties"/>
</body>
</html>
Method Description
Example:
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
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'>
document.getElementById("demo").innerHTML = txt;
</script>
</body>
Screen Object
Property Description
Example:
<!doctype html>
<body>
<script type="text/javascript">
</script>
</body>
It contains the URLs visited by the user . It is part of the window object and is accessed through the
window.history property.
Property Description
Method Description
back() Loads the previous URL in the history list
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">
</script>
</body>
</html>
The back() method loads the previous URL in the history list.
Syntax: history.back()
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>
</body>
</html>
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>
</body>
It contains the URLs visited by the user . It is part of the window object and is accessed through the
window.history property.
Property Description
Method Description
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">
</script>
</body>
</html>
The back() method loads the previous URL in the history list.
Syntax: history.back()
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>
</body>
</html>
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>
</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.
Property Description
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>
Method Description
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>
</body>
</html>
Document Object
Each HTML document loaded into a browser window becomes a Document object. It has the
following list of properties..!!
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:
<html>
<body>
<p>Number of anchors:
<script>
document.write(document.anchors.length);
</script></p>
</body>
</html>
<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>
<html>
<body>
<p>Number of images:
<script>
document.write(document.images.length);
</script></p>
</body>
</html
<html>
<body>
<script>
document.write(document.images[0].id);
</script></p>
</body>
</html>
<html>
<body>
<script>
document.write(document.cookie);
</script>
</body>
</html>
<html>
<head>
<title>My title</title>
</head>
<body>
<script>
document.write(document.title);
</script>
</body>
</html>
<html>
<body>
<script>
document.write(document.URL);
</script>
</body>
</html>
<head>
<title>My WebPage</title>
</head>
<body>
<script type='text/javascript'>
document.write(document.title);
</script>
</body>
</html>
Container Tags :
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
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>
<br/>
</body>
Example:
<head>
<script type='text/javascript'>
function fun1()
{
alert(document.getElementById('txtarea1').value);
alert(document.getElementById('p1').innerHTML);
</script>
</head>
<body>
<textarea id='txtarea1'></textarea>
<br/>
</body>
"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).
Declared at the beginning of a JavaScript file, it has global scope (all code will execute in strict
mode):
Example:
<body>
<script>
"use strict";
</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.
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.
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.
Attribute Description
<!doctype html>
<head>
<script type='text/javascript'>
function notEmpty()
if(myTextField.value != "")
else
</script>
</head>
<body>
<form action='nit.html'>
</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.
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.
Attribute Description
disabled Specifies that the input element should be disabled
Example:
<!doctype html>
<head>
<script type='text/javascript'>
function notEmpty()
if(myTextField.value != "")
{
else
</script>
</head>
<body>
<form action='nit.html'>
</form>
</body>
Example:
<!doctype html>
<body>
</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>
Last name:<br>
</form>
</body>
Disable Button
<!doctype html>
<head>
<script>
function disableElement()
document.getElementById("secondbtn").disabled=true;
</script>
</head>
<body>
<form>
Buttons:<br/>
</form>
</body>
<!doctype html>
<body>
<script>
document.write(document.getElementById("button1").value);
</script></p>
</body>
<!doctype html>
<head>
<script>
var myWindow;
function openWin()
}
function closeWin()
myWindow.close();
</script>
</head>
<body>
</body>
<!doctype html>
<head>
<script type="text/javascript">
function validate()
var r1 = document.getElementById('male').checked;
var r2 = document.getElementById('female').checked;
return false;
return true;
</script>
</head>
<body>
You are?
</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.
2. The at symbol @
4. A period
5. The top level domain (com, net, org, us, gov, ...)
Valid Examples:
<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>
<br>
<br/>
</body>
---------------------------------------------------------------------END-----------------------------------------------------------
------------