0% found this document useful (0 votes)
8 views66 pages

Java Script

Uploaded by

srusti P D
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views66 pages

Java Script

Uploaded by

srusti P D
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 66

What is JavaScript ?

JavaScript is a dynamic computer programming language. It is lightweight and most

commonly used as a part of web pages, whose implementations allow client-side

script to interact with the user and make dynamic pages. It is an interpreted

programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,

possibly because of the excitement being generated by Java. JavaScript made its first

appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose

core of the language has been embedded in Netscape, Internet Explorer, and other

web browsers. JavaScript is a lightweight, interpreted programming language. It is

designed for creating network-centric applications. It is complimentary to and

integrated with Java. JavaScript is very easy to implement because it is integrated with

HTML. It is open and cross-platform.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be

included in or referenced by an HTML document for the code to be interpreted by the

browser.

It means that a web page need not be a static HTML, but can include programs that

interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI

server-side scripts. For example, you might use JavaScript to check if the user has

entered a valid e-mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the

entries are valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link

navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript
The merits of using JavaScript are −

● Less server interaction − You can validate user input

before sending the page off to the server. This saves

server traffic, which means less load on your server.

● Immediate feedback to the visitors − They don't have to

wait for a page reload to see if they have forgotten to

enter something.

● Increased interactivity − You can create interfaces that

react when the user hovers over them with a mouse or

activates them via the keyboard.

● Richer interfaces − You can use JavaScript to include such

items as drag-and-drop components and sliders to give a

Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It

lacks the following important features −

● Client-side JavaScript does not allow the reading or writing of files. This

has been kept for security reasons.

● JavaScript cannot be used for networking applications because there is no

such support available.

● JavaScript doesn't have any multithreading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows

you to build interactivity into otherwise static HTML pages.

Why to Learn Javascript


Javascript is a MUST for students and working professionals to become a great

Software Engineer specially when they are working in Web Development Domain. I

will list down some of the key advantages of learning Javascript:

● Javascript is the most popular programming language in the world and

that makes it a programmer’s great choice. Once you learn Javascript, it

helps you develop great front-end as well as back-end softwares using

different Javascript based frameworks like jQuery, Node.JS etc.

● Javascript is everywhere, it comes installed on every modern web

browser and so to learn Javascript you really do not need any special
environment setup. For example Chrome, Mozilla Firefox , Safari and

every browser you know as of today, supports Javascript.

● Javascript helps you create really beautiful and crazy fast websites. You

can develop your website with a console like look and feel and give your

users the best Graphical User Experience.

● JavaScript usage has now extended to mobile app development, desktop

app development, and game development. This opens many

opportunities for you as a Javascript Programmer.

● Due to high demand, there is tons of job growth and high pay for those

who know JavaScript. You can navigate over to different job sites to see

what having JavaScript skills looks like in the job market.

● Great thing about Javascript is that you will find tons of frameworks and

Libraries already developed which can be used directly in your software

development to reduce your time to market.

JavaScript Development Tools


● Microsoft FrontPage − Microsoft has developed a popular

HTML editor called FrontPage. FrontPage also provides web

developers with a number of JavaScript tools to assist in

the creation of interactive websites.

● Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a

very popular HTML and JavaScript editor in the professional

web development crowd. It provides several handy prebuilt


JavaScript components, integrates well with databases, and

conforms to new standards such as XHTML and XML.

● Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and

JavaScript editor from Macromedia that can be used to

manage personal websites effectively.

JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are placed within the

<script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web

page, but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between

these tags as a script. A simple syntax of your JavaScript will appear as follows

<script ...>

JavaScript code

</script>

The script tag takes two important attributes −

● Language − This attribute specifies what scripting language

you are using. Typically, its value will be javascript.


Although recent versions of HTML (and XHTML, its successor)

have phased out the use of this attribute.

● Type − This attribute is what is now recommended to

indicate the scripting language in use and its value should

be set to "text/javascript".

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


JavaScript code
</script>

● Any text between a // and the end of a line is treated as a comment and is

ignored by JavaScript.

● Any text between the characters /* and */ is treated as a comment. This may

span multiple lines.

● JavaScript also recognizes the HTML comment opening sequence <!--.

JavaScript treats this as a single-line comment, just as it does the // comment.

● The HTML comment closing sequence --> is not recognized by JavaScript so it

should be written as //-->.


<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++

/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

Hello World using Javascript

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Applications of Javascript Programming


● Client side validation - This is really important to verify any user input

before submitting it to the server and Javascript plays an important role in

validating those inputs at the front-end itself.


● Manipulating HTML Pages - Javascript helps in manipulating HTML pages

on the fly. This helps in adding and deleting any HTML tag very easily

using javascript and modifying your HTML to change its look and feel

based on different devices and requirements.

● User Notifications - You can use Javascript to raise dynamic pop-ups on

the webpages to give different types of notifications to your website

visitors.

● Back-end Data Loading - Javascript provides Ajax library which helps in

loading back-end data while you are doing some other processing. This

really gives an amazing experience to your website visitors.

● Presentations - JavaScript also provides the facility of creating

presentations which gives the website look and feel. JavaScript provides

RevealJS and BespokeJS libraries to build web-based slide presentations.

● Server Applications - Node JS is built on Chrome's Javascript runtime for

building fast and scalable network applications. This is an event based

library which helps in developing very sophisticated server applications

including Web Servers.

Enabling JavaScript in Browsers

JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox −

● Open a new tab → type about: config in the address bar.

● Then you will find the warning dialog. Select I’ll be careful, I promise!
● Then you will find the list of configure options in the browser.

● In the search bar, type javascript.enabled.

● There you will find the option to enable or disable

javascript by right-clicking on the value of that option →

select toggle.

JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome −

● Click the Chrome menu at the top right hand corner of your browser.

● Select Settings.

● Click Show advanced settings at the end of the page.

● Under the Privacy section, click the Content settings button.

● In the "Javascript" section, select "Do not allow any site to run JavaScript"

or "Allow all sites to run JavaScript (recommended)".

Warning for Non-JavaScript Browsers


If you have to do something important using JavaScript, then you can display a warning

message to the user using <noscript> tags.

You can add a noscript block immediately after the script block as

follows −

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>

JavaScript - Placement in HTML File


There is a flexibility given to include JavaScript code anywhere in

an HTML document. However the most preferred ways to include

JavaScript in an HTML file are as follows −

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

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

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

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

JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user

clicks somewhere, then you will place that script in the head as

follows −

<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

JavaScript in <body>...</body> section

<html>
<head>
</head>

<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<p>This is web page body </p>


</body>
</html>

JavaScript in <body> and <head> Sections


<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>

JavaScript Variable Scope


<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

JavaScript Operators

<html>
<body>

<script type = "text/javascript">


<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>

Set the variables to different values and then try...


</body>
</html>

Using Comparison Operators

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>

typeof Operator
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

JavaScript - if...else Statement


<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");


break;

case 'C': document.write("Passed<br />");


break;

case 'D': document.write("Not so good<br />");


break;

case 'F': document.write("Failed<br />");


break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Looping

<html>
<body>

<script type = "text/javascript">


<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

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


do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

JavaScript for...in loop

Syntax
The syntax of ‘for..in’ loop is −
for (variablename in object) {
statement or block to execute
}
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Using Labels to Control the Flow


A label is simply an identifier followed by a colon (:) that is applied to a statement or a

block of code. We will see two different examples to understand how to use labels

with break and continue.

Note − Line breaks are not allowed between the ‘continue’ or ‘break’

statement and its label name. Also, there should not be any other

statement in between a label name and associated loop.

<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>

<html>
<body>

<script type = "text/javascript">


<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name

for (var i = 0; i < 3; i++) {


document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>

JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program.

This eliminates the need of writing the same code again and again. It helps

programmers in writing modular codes. Functions allow a programmer to divide a big

program into a number of small and manageable functions.


Like any other advanced programming language, JavaScript also supports all the

features necessary to write modular code using functions. You must have seen

functions like alert() and write() in the earlier chapters.

Function Definition
Before we use a function, we need to define it. The most common way to define a

function in JavaScript is by using the function keyword, followed by a unique function

name, a list of parameters (that might be empty), and a statement block surrounded by

curly braces.

Syntax
The basic syntax is shown here.

<script type = "text/javascript">


<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

<script type = "text/javascript">


<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the

name of that function as shown in the following code.

<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('AB', 'CD');
document.write (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
JavaScript - Events

What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user

or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too

is an event. Other examples include events like pressing any key, closing a window,

resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which cause

buttons to close windows, messages to be displayed to users, data to be validated,

and virtually any other type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML

element contains a set of events which can trigger JavaScript Code.

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left

button of his mouse. You can put your validation, warning etc., against this event type.

Example

<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your form

validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate()

function before submitting a form data to the webserver. If validate() function returns

true, the form will be submitted, otherwise it will not submit the data.

<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text
as well. The onmouseover event triggers when you bring your mouse over any
element and the onmouseout triggers when you move your mouse out from that
element.
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

HTML 5 Standard Events


The standard HTML 5 events are listed here for your reference. Here script indicates a

Javascript function to be executed against that event.

Attribute Valu Description


e

Offline script Triggers when the document goes offline

Onabort script Triggers on an abort event


onafterprint script Triggers after the document is printed

onbeforeonload script Triggers before the document loads

onbeforeprint script Triggers before the document is printed

onblur script Triggers when the window loses focus

Triggers when media can start play, but might has to stop
oncanplay script
for buffering

Triggers when media can be played to the end, without


oncanplaythrough script
stopping for buffering

onchange script Triggers when an element changes

onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is triggered

ondblclick script Triggers on a mouse double-click

ondrag script Triggers when an element is dragged

ondragend script Triggers at the end of a drag operation

Triggers when an element has been dragged to a valid


ondragenter script
drop target

Triggers when an element is being dragged over a valid


ondragleave script
drop target

ondragover script Triggers at the start of a drag operation

ondragstart script Triggers at the start of a drag operation


ondrop script Triggers when dragged element is being dropped

ondurationchange script Triggers when the length of the media is changed

Triggers when a media resource element suddenly


onemptied script
becomes empty.

onended script Triggers when media has reach the end

onerror script Triggers when an error occur

onfocus script Triggers when the window gets focus

onformchange script Triggers when a form changes

onforminput script Triggers when a form gets user input

onhaschange script Triggers when the document has change

oninput script Triggers when an element gets user input

oninvalid script Triggers when an element is invalid

onkeydown script Triggers when a key is pressed

onkeypress script Triggers when a key is pressed and released

onkeyup script Triggers when a key is released

onload script Triggers when the document loads

onloadeddata script Triggers when media data is loaded

Triggers when the duration and other media data of a


onloadedmetadata script
media element is loaded

onloadstart script Triggers when the browser starts to load the media data
onmessage script Triggers when the message is triggered

onmousedown script Triggers when a mouse button is pressed

onmousemove script Triggers when the mouse pointer moves

onmouseout script Triggers when the mouse pointer moves out of an element

onmouseover script Triggers when the mouse pointer moves over an element

onmouseup script Triggers when a mouse button is released

onmousewheel script Triggers when the mouse wheel is being rotated

onoffline script Triggers when the document goes offline

onoine script Triggers when the document comes online

ononline script Triggers when the document comes online

onpagehide script Triggers when the window is hidden

onpageshow script Triggers when the window becomes visible

onpause script Triggers when media data is paused

onplay script Triggers when media data is going to start playing

onplaying script Triggers when media data has start playing

onpopstate script Triggers when the window's history changes

onprogress script Triggers when the browser is fetching the media data

onratechange script Triggers when the media data's playing rate has changed
onreadystatechang script Triggers when the ready-state changes
e

onredo script Triggers when the document performs a redo

onresize script Triggers when the window is resized

onscroll script Triggers when an element's scrollbar is being scrolled

Triggers when a media element's seeking attribute is no


onseeked script
longer true, and the seeking has ended

Triggers when a media element's seeking attribute is true,


onseeking script
and the seeking has begun

onselect script Triggers when an element is selected

onstalled script Triggers when there is an error in fetching media data

onstorage script Triggers when a document loads

onsubmit script Triggers when a form is submitted

Triggers when the browser has been fetching media data,


onsuspend script
but stopped before the entire media file was fetched

ontimeupdate script Triggers when media changes its playing position

onundo script Triggers when a document performs an undo

onunload script Triggers when the user leaves the document

Triggers when media changes the volume, also when


onvolumechange script
volume is set to "mute"

onwaiting script Triggers when media has stopped playing, but is expected
to resume

JavaScript and Cookies

What are Cookies ?


Web Browsers and Servers use HTTP protocol to communicate and HTTP is a

stateless protocol. But for a commercial website, it is required to maintain session

information among different pages. For example, one user registration ends after

completing many pages. But how to maintain users' session information across all the

web pages.

In many situations, using cookies is the most efficient method of remembering and

tracking preferences, purchases, commissions, and other information required for

better visitor experience or site statistics.

How It Works ?
Your server sends some data to the visitor's browser in the form of a cookie. The

browser may accept the cookie. If it does, it is stored as a plain text record on the

visitor's hard drive. Now, when the visitor arrives at another page on your site, the

browser sends the same cookie to the server for retrieval. Once retrieved, your server

knows/remembers what was stored earlier.

Cookies are a plain text data record of 5 variable-length fields −


● Expires − The date the cookie will expire. If this is

blank, the cookie will expire when the visitor quits the

browser.

● Domain − The domain name of your site.

● Path − The path to the directory or web page that set the

cookie. This may be blank if you want to retrieve the

cookie from any directory or page.

● Secure − If this field contains the word "secure", then the

cookie may only be retrieved with a secure server. If this

field is blank, no such restriction exists.

● Name=Value − Cookies are set and retrieved in the form of

key-value pairs

Cookies were originally designed for CGI programming. The data contained in a cookie

is automatically transmitted between the web browser and the web server, so CGI

scripts on the server can read and write cookie values that are stored on the client.

JavaScript can also manipulate cookies using the cookie property of the Document

object. JavaScript can read, create, modify, and delete the cookies that apply to the

current web page.

Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie

object, which looks like this.

document.cookie = "key1 = value1;key2 = value2;expires = date";


Here the expires attribute is optional. If you provide this attribute with a valid date or

time, then the cookie will expire on a given date or time and thereafter, the cookies'

value will not be accessible.

Note − Cookie values may not include semicolons, commas, or

whitespace. For this reason, you may want to use the JavaScript

escape() function to encode the value before storing it in the

cookie. If you do this, you will also have to use the corresponding

unescape() function when you read the cookie value.

Example

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>

Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the

document.cookie object is the cookie. So you can use this string whenever you want to

access the cookie. The document.cookie string will keep a list of name=value pairs

separated by semicolons, where name is the name of a cookie and value is its string

value.

You can use strings' split() function to break a string into key and

values as follows −

<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );

// Get all the cookies pairs in an array


cookiearray = allcookies.split(';');

// Now take key value pair out of this array


for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>

Setting Cookies Expiry Date


You can extend the life of a cookie beyond the current browser session by setting an

expiration date and saving the expiry date within the cookie. This can be done by

setting the ‘expires’ attribute to a date and time.

Example : It illustrates how to extend the expiry date of a cookie by 1 Month.

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the

cookie return nothing. To do this, you just need to set the expiry date to a time in the

past.

Example

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

JavaScript - Page Redirection

What is Page Redirection ?


You might have encountered a situation where you clicked a URL to reach a page X but

internally you were directed to another page Y. It happens due to page redirection. This

concept is different from JavaScript Page Refresh.

There could be various reasons why you would like to redirect a user

from the original page. We are listing down a few of the reasons −

● You did not like the name of your domain and you are moving to a new

one. In such a scenario, you may want to direct all your visitors to the new

site. Here you can maintain your old domain but put a single page with a

page redirection such that all your old domain visitors can come to your

new domain.

● You have built-up various pages based on browser versions or their

names or may be based on different countries, then instead of using your

server-side page redirection, you can use client-side page redirection to

land your users on the appropriate page.

● The Search Engines may have already indexed your pages. But while

moving to another domain, you would not like to lose your visitors coming
through search engines. So you can use client-side page redirection. But

keep in mind this should not be done to fool the search engine, it could

lead your site to get banned.

How Page Re-direction Works ?


To redirect your site visitors to a new page, you just need to add a line in your head
section as follows

<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://aitckm.in/";
}
//-->
</script>
</head>

<body>
<p>Click the following button, you will be redirected to home page.</p>

<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>

</body>
</html>

Example 2
You can show an appropriate message to your site visitors before redirecting them to a

new page. This would need a bit time delay to load a new page. The following
example shows how to implement the same. Here setTimeout() is a built-in JavaScript

function which can be used to execute another function after a given time interval.

<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://aitckm.in/";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

<body>
</body>
</html>

Example 3
The following example shows how to redirect your site visitors onto a different page

based on their browsers.

<html>
<head>
<script type = "text/javascript">
<!--
var browsername = navigator.appName;
if( browsername == "Google Chrome" ) {
window.location = "https://aitckm.in/";
} else if ( browsername =="Microsoft Internet Explorer") {
window.location = "https://www.google.com/";
} else {
window.location = "https://nieit.ac.in/";
}
//-->
</script>
</head>

<body>
</body>
</html>

JavaScript - Dialog Boxes


JavaScript supports three important types of dialog boxes. These dialog boxes can be
used to raise and alert, or to get confirmation on any input or to have a kind of input
from the users. Here we will discuss each dialog box one by one.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users. For

example, if one input field requires to enter some text but the user does not provide

any input, then as a part of validation, you can use an alert box to give a warning

message.

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only

one button "OK" to select and proceed.


<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It

displays a dialog box with two buttons: OK and Cancel.

If the user clicks on the OK button, the window method confirm() will return true. If the

user clicks on the Cancel button, then confirm() returns false. You can use a

confirmation dialog box as follows.

<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user

input. Thus, it enables you to interact with the user. The user needs to fill in the field

and then click OK.

This dialog box is displayed using a method called prompt() which takes two

parameters: (i) a label which you want to display in the text box and (ii) a default string

to display in the text box.


This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the

window method prompt() will return the entered value from the text box. If the user

clicks the Cancel button, the window method prompt() returns null.

<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

JavaScript - Void Keyword


void is an important keyword in JavaScript which can be used as a unary operator that

appears before its single operand, which may be of any type. This operator specifies an

expression to be evaluated without returning a value.

<head>
<script type = "text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>

Example 1
The most common use of this operator is in a client-side javascript: URL, where it

allows you to evaluate an expression for its side-effects without the browser

displaying the value of the evaluated expression.

Here the expression alert ('Warning!!!') is evaluated but it is not

loaded back into the current document −

<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
</html>

Example 2
Take a look at the following example. The following link does nothing because the

expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is

not loaded back into the current document.

<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<p>Click the following, This won't react at all...</p>
<a href = "javascript:void(0)">Click me!</a>
</body>
</html>

Example 3
Another use of void is to purposely generate the undefined value as follows.

<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var a,b,c;

a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

JavaScript - Page Printing


Many times you would like to place a button on your webpage to print the content of

that web page via an actual printer. JavaScript helps you to implement this

functionality using the print function of window object.


The JavaScript print function window.print() prints the current web page when

executed. You can call this function directly using the onclick event as shown in the

following example.

<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>

<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>

JavaScript - Objects Overview


JavaScript is an Object Oriented Programming (OOP) language. A

programming language can be called object-oriented if it provides

four basic capabilities to developers −


● Encapsulation − the capability to store related

information, whether data or methods, together in an

object.

● Aggregation − the capability to store one object inside

another object.

● Inheritance − the capability of a class to rely upon

another class (or number of classes) for some of its

properties and methods.

● Polymorphism − the capability to write one function or

method that works in a variety of different ways.

Object Properties
Object properties can be any of the three primitive data types, or any of the abstract

data types, such as another object. Object properties are usually variables that are

used internally in the object's methods, but can also be globally visible variables that

are used throughout the page.

The syntax for adding a property to an object is −

objectName.objectProperty = propertyValue;

Object Methods
Methods are the functions that let the object do something or let something be done to

it. There is a small difference between a function and a method – at a function is a


standalone unit of statements and a method is attached to an object and can be

referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object to the

screen to performing complex mathematical operations on a group of local properties

and parameters.

For example − Following is a simple example to show how to use the

write() method of document object to write any content on the

document.

document.write("This is test");

User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called

Object.

The new Operator


The new operator is used to create an instance of an object. To create an object, the

new operator is followed by the constructor method.

In the following example, the constructor methods are Object(), Array(), and Date().

These constructors are built-in JavaScript functions.

var employee = new Object();

var books = new Array("C", "C++", "Java");


var day = new Date("August 15, 1947");

The Object() Constructor


A constructor is a function that creates and initializes an object. JavaScript provides a

special constructor function called Object() to build the object. The return value of the

Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned to the

object are not variables and are not defined with the var keyword.

Example 1

Demonstrates how to create an Object.

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

Example 2
Demonstrates how to create an object with a User-Defined Function. Here this

keyword is used to refer to the object that has been passed to a function.

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

JavaScript - Document Object Model or DOM


Every web page resides inside a browser window which can be considered as an

object.

A Document object represents the HTML document that is displayed in that window.

The Document object has various properties that refer to other objects which allow

access to and modification of document content.

The way a document content is accessed and modified is called the Document Object

Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure

applies to the organization of objects in a Web document.

● Window object − Top of the hierarchy. It is the outmost

element of the object hierarchy.

● Document object − Each HTML document that gets loaded into

a window becomes a document object. The document contains

the contents of the page.

● Form object − Everything enclosed in the <form>...</form>

tags sets the form object.

● Form control elements − The form object contains all the

elements defined for that object such as text fields,

buttons, radio buttons, and checkboxes.

Here is a simple hierarchy of a few important objects −


There are several DOMs in existence. The following sections explain each of these

DOMs in detail and describe how you can use them to access and modify document

content.

● The Legacy DOM − This is the model which was introduced in

early versions of JavaScript language. It is well supported

by all browsers, but allows access only to certain key

portions of documents, such as forms, form elements, and

images.

● The W3C DOM − This document object model allows access

and modification of all document content and is

standardized by the World Wide Web Consortium (W3C). This

model is supported by almost all the modern browsers.

● The IE4 DOM − This document object model was introduced in

Version 4 of Microsoft's Internet Explorer browser. IE 5

and later versions include support for most basic W3C DOM

features.
JavaScript - Errors & Exceptions Handling
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors,

and (c) Logical Errors.

Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional

programming languages and at interpret time in JavaScript.

For example, the following line causes a syntax error because it is missing a closing

parenthesis.

<script type = "text/javascript">


<!--
window.print(;
//-->
</script>

When a syntax error occurs in JavaScript, only the code contained within the same
thread as the syntax error is affected and the rest of the code in other threads gets
executed assuming nothing in them depends on the code containing the error.

Runtime Errors
Runtime errors, also called exceptions, occur during execution (after

compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is

correct, but at runtime, it is trying to call a method that does not exist.

<script type = "text/javascript">


<!--
window.printme();
//-->
</script>

Exceptions also affect the thread in which they occur, allowing other JavaScript threads

to continue normal execution.

Logical Errors
Logic 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 cannot catch those errors, because it depends on your business requirement what

type of logic you want to put in your program.

The try...catch...finally Statement


The latest versions of JavaScript added exception handling capabilities. JavaScript

implements the try...catch...finally construct as well as the throw operator to handle

exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch

JavaScript syntax errors.

Here is the try...catch...finally block syntax −


<script type = "text/javascript">
<!--
try {
// Code to run
[break;]
}

catch ( e ) {
// Code to run if an exception occurs
[break;]
}

[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

JavaScript - Form Validation


Form validation normally used to occur at the server, after the client had entered all

the necessary data and then pressed the Submit button. If the data entered by a client

was incorrect or was simply missing, the server would have to send all the data back

to the client and request that the form be resubmitted with correct information. This

was really a lengthy process which used to put a lot of burden on the server.

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 − First of all, the form must be checked

to make sure all the mandatory fields are filled in. It

would require just a loop through each field in the form

and check for data.

● Data Format Validation − Secondly, the data that is entered

must be checked for correct form and value. Your code must

include appropriate logic to test correctness of data.

<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>

Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are calling

validate() to validate data when onsubmit event is occurring. The following code

shows the implementation of this validate() function.


<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

Data Format Validation


Now we will see how we can validate our entered form data before submitting it to the

web server.
The following example shows how to validate an entered email address. An email

address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first

character of the email address, and the last dot must at least be one character after the

‘@’ sign.

<script type = "text/javascript">


<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
JavaScript - Animation
You can use JavaScript to create a complex animation having, but not

limited to, the following elements −

● Fireworks

● Fade Effect

● Roll-in or Roll-out

● Page-in or Page-out

● Object movements

You might also like