Java Script
Java Script
script to interact with the user and make dynamic pages. It is an interpreted
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
integrated with Java. JavaScript is very easy to implement because it is integrated with
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
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
The JavaScript code is executed when the user submits the form, and only if all the
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 −
enter something.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It
● Client-side JavaScript does not allow the reading or writing of files. This
Software Engineer specially when they are working in Web Development Domain. I
browser and so to learn Javascript you really do not need any special
environment setup. For example Chrome, Mozilla Firefox , Safari and
● 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
● 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
● Great thing about Javascript is that you will find tons of frameworks and
JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are placed within the
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>
be set to "text/javascript".
● 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
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
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
visitors.
loading back-end data while you are doing some other processing. This
presentations which gives the website look and feel. JavaScript provides
JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox −
● 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.
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.
● In the "Javascript" section, select "Do not allow any site to run JavaScript"
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>
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>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
JavaScript Operators
<html>
<body>
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>
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
typeof Operator
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
<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;
Looping
<html>
<body>
document.write("Loop stopped!");
//-->
</script>
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
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 /> ");
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
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>
block of code. We will see two different examples to understand how to use labels
Note − Line breaks are not allowed between the ‘continue’ or ‘break’
statement and its label name. Also, there should not be any other
<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>
</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
features necessary to write modular code using functions. You must have seen
Function Definition
Before we use a function, we need to define it. The most common way to define a
name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.
Syntax
The basic syntax is shown here.
<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
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,
Developers can use these events to execute JavaScript coded responses, which cause
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
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>
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>
<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>
Triggers when media can start play, but might has to stop
oncanplay script
for buffering
onloadstart script Triggers when the browser starts to load the media data
onmessage script Triggers when the message is triggered
onmouseout script Triggers when the mouse pointer moves out of an element
onmouseover script Triggers when the mouse pointer moves over an element
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
onwaiting script Triggers when media has stopped playing, but is expected
to resume
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
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
blank, the cookie will expire when the visitor quits the
browser.
● Path − The path to the directory or web page that set the
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
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie
time, then the cookie will expire on a given date or time and thereafter, the cookies'
whitespace. For this reason, you may want to use the JavaScript
cookie. If you do this, you will also have to use the corresponding
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 );
<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>
expiration date and saving the expiry date within the cookie. This can be done by
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
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) + ";"
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
internally you were directed to another page Y. It happens due to page redirection. This
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.
● 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
<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
<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>
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
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
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
<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>
input. Thus, it enables you to interact with the user. The user needs to fill in the field
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
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>
appears before its single operand, which may be of any type. This operator specifies an
<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
<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
<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>
that web page via an actual printer. JavaScript helps you to implement this
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>
object.
another object.
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
objectName.objectProperty = propertyValue;
Object Methods
Methods are the functions that let the object do something or let something be done to
Methods are useful for everything from displaying the contents of the object to the
and parameters.
document.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called
Object.
In the following example, the constructor methods are Object(), Array(), and Date().
special constructor function called Object() to build the object. The return value of the
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
<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>
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
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
DOMs in detail and describe how you can use them to access and modify document
content.
images.
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,
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
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.
Exceptions also affect the thread in which they occur, allowing other JavaScript threads
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
exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
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
must be checked for correct form and value. Your code must
<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>
validate() to validate data when onsubmit event is occurring. The following code
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.
● Fireworks
● Fade Effect
● Roll-in or Roll-out
● Page-in or Page-out
● Object movements