AIIT
Amity Institute Of
Information Technology
Advanced Web Technologies and
Applications
Dr Monika Sharma
1
AIIT
JAVA SCRIPT
INTRODUCTION AIIT
• JavaScript started life as LiveScript, but Netscape changed the
name, possibly because of the excitement being generated by Java
to JavaScript.
• JavaScript made its first appearance in Netscape 2.0 in 1995 with
a name LiveScript.
• JavaScript is a lightweight, interpreted programming language
with object oriented capabilities that allows you to build
interactivity into otherwise static HTML pages.
• The general-purpose core of the language has been embedded in
Netscape,Internet Explorer, and other web browsers
INTRODUCTION AIIT
JavaScript scripting language
• Enhances functionality and appearance
• JavaScript is most popular for writing
scripts for client-side applications over
other script languages
• Makes pages more dynamic and
interactive
• JavaScript is mainly based on the HTML
•Attributes (data) and behaviors (methods)
are associated with the object.
Cont… AIIT
• Similar syntax to C, C++, and Java
• Interpreted, scripting language, not a full programming
language
• Platform-independent.
• Not really related to Java.
• Both client-side (browser-based) JavaScript and
server-side JavaScript. Most focus is on the client.
AIIT
Java script document Object model
• 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
AIIT
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 in detail and describe how you can use
them to access and modify document content.
AIIT
. 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.
AIIT
A JavaScript consists of JavaScript statements that are placed
within the
<script>... </script> HTML tags in a web page.
You can place the <script> tag containing your JavaScript
anywhere within you web page but it is preferred way to keep it
within the <head> tags. The <script> tag alert the browser program
to begin interpreting all the text between these tags as a script. So
simple syntax of your JavaScript will be as follows:
<script ...>
JavaScript code
</script>
AIIT
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>
AIIT
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
[Link]("Hello World!")
//-->
</script></body></html>
Use of Java Script AIIT
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
Java Script Applications AIIT
• We can create client-side forms with validations of
form’s fields
• We can create many interactive games and multimedia
applications
• We can create digital clocks which shows client-side
time rather server-side time.
AIIT
Starting Java Script
• To begin JavaScript we need
– Text Editor
– Browser
– To run JavaScript we need a compatible browser like crome
and up
AIIT
First program
• One way to put JavaScript in a page is with the
<SCRIPT> tag
• Start tag with <SCRIPT LANGUAGE="javascript">
• End tag with </SCRIPT>
Put JavaScript between the tags.
AIIT
Example
• <SCRIPT LANGUAGE="javascript">
[Link]("Hello, world")
</SCRIPT>
Output:
• Hello, world
AIIT
Prog…
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
[Link]("Welcome!!! You are
now learning JavaScript.");
</script>
</head>
<body>
</body>
</html>
How to add comments in AIIT
java script
• JavaScript supports both C-style and C++-style comments.
• 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 //-->.
AIIT
Comment Statements
• Comment statements are used to prevent the browser
from executing certain parts of code that you designate
as non-code.
• The single line comment is just two slashes (//) and the
multiple line comment starts with (/*) and ends with (*/).
We will talk about comments in greater depth in a later
lesson.
AIIT
Single Line comments
• <script type="text/javascript">
<!-- // This is a single line JavaScript comment
[Link]("I have comments in my JavaScript
code!");
//[Link]("You can't see this!"); //--> </script>
Output AIIT
• I have comments in my JavaScript code!
AIIT
Programming with JavaScript (1)
• A statement should end with a
semicolon (;).
• JavaScript is case sensitive.
• writeln method writes a line in the
document
[Link](“<h1>welcome</h1>”
);
AIIT
<SCRIPT LANGUAGE="javascript">
// This JavaScript illustrates some simple concepts
[Link]("<B>Hello, bold world</B><BR>")
// Print text with an HTML tag
[Link]("Two plus two is " + (2+2) + "<BR>")
// Print the result of a mathematical expression
[Link]("Your browser says it is: "\" +
[Link] + "\"<BR>")
// Print one of the browser properties.
</SCRIPT>
AIIT
Programming with JavaScript (2)
Escape character ( \ )
Indicates “special” character is used in the
string
window object : a browser window.
A Window object is created automatically with
every instance of a<body> or<frameset> tag
alert method creates a Dialog box
[Link](“welcome”);
Simple JavaScript Program AIIT
Inline scripting
Written in the <body> or<head> of the document
<script> tag
JavaScript Single-line comment symbol: //
Example:
<script type=“text/javascript”>>
<!—
Script code here
//→
</script>
AIIT
DATA TYPES OF JAVASCRIPT
JavaScript provides different data types to
hold different types of values. There are two
types of data types in JavaScript.
• Primitive data type
• Non-primitive (reference) data type
Example:-var a=40;//holding number
var b="Rahul";//holding string
AIIT
Significance of variant data type
JavaScript allows you to work with three
primitive data types:
• Numbers eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
AIIT
Primitive Data Type
Primitive Data Type:-Data types that can be support
only single value is called Primitive data type . It
includes three types:-
JavaScript Strings:A string (or a text string) is a series
of characters like "John Doe".Strings are written with
quotes. You can use single or double quotes:
Example:
var carName = "Volvo XC60"; // Using double
quotes
var carName = 'Volvo XC60'; // Using single quotes
EXAMPLE AIIT
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
[Link]("demo").innerHTML =
carName1 + "<br>" +
carName2 + "<br>" +
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>
AIIT
2. JavaScript Numbers:-JavaScript has only one type of
[Link] can be written with, or without decimals:
Example
• var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var x1 = 34.00;
var x2 = 34;
var y = 123e5;
var z = 123e-5;
[Link]("demo").innerHTML = x1 + "<br>" + x2 + "<br>" + y +
"<br>" + z
AIIT
3. JavaScript Booleans:-Booleans can only have two values:
true or false.
Example
• var x = true;
var y = false;
<!DOCTYPE html>
<html>
<body>
<p>Display the value of Boolean(10 > 9):</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction(){ [Link]("demo").innerHTML =
Boolean(10 > 9);
}
</script>
</body>
AIIT
4. Null:-In JavaScript null is "nothing". It is supposed to be something that
doesn't [Link], in JavaScript, the data type of null is an
[Link] can consider it a bug in JavaScript that typeof null is an object.
It should be [Link] can empty an object by setting it to null:
• Example
<!DOCTYPE html>
<html>
<body>
<p>Objects can be emptied by setting the value to <b>null</b>.</p>
<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
var person = null;
[Link]("demo").innerHTML = typeof person;
AIIT
[Link]:-In JavaScript, a variable without a value, has the
value undefined. The typeof is also undefined.
Example
<!DOCTYPE html>
<html>
<body>
<p>Both the value, and the data type, of a variable with no value is
<b>undefined</b>.</p>
<p id="demo"></p>
<script>
var person;
[Link]("demo").innerHTML =
person + "<br>" + typeof person;
</script>
</body>
</html>
Non-Primitive Data Types AIIT
AIIT
Non-Primitive are of two types:-
[Link]:- JavaScript arrays are used to store multiple values in a
single variable.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;
</script>
</body>
OBJECT AIIT
An object is a collection of properties, and a
property is an association between a name (or
key) and a value. A property's value can be a
function, in which case the property is known
as a method. In addition to objects that are
predefined in the browser, you can define
your own objects.
AIIT
2. Objects:-JavaScript objects are written with curly
[Link] properties are written as name:value pairs,
separated by commas.
• Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
AIIT
age : 50,
eyeColor : "blue"
};
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
Variables AIIT
Variables are used to store data.
• Keyword : var
• A variable's value can change during the script.
• You can refer to a variable by name to see its
value or to change its value.
• Name of a variable : a series of characters
• letters, digits, underscores( _ ) and dollar signs
($)
• no white space
• not begin with a digit
• not a keyword.
AIIT
How to declare Variable in Java Script
<script language="javascript"
type="text/javascript">
<!--
Var var1 = 10;
Var var2 = 20;
//-->
</script>
Use Variables AIIT
Declare a variable:
• var name;
• var size;
• var name, size;
• Assign a value to a
variable:
• name = “Lisa”;
• size = 20;
• Combine two steps:
• var name = “Lisa”;
Cont… AIIT
• Variables are declared with the var keyword:
• var num = “1”;
• var name = “Mel”;
• var phone = “123-456-7890”;
AIIT
Types of creating variables
• var x1 = 'He said "be seeing you" as he left.'
• [Link](x1)
• x = "New Message“
• [Link](x1)
Example AIIT
<script language=“JavaScript”>
<!-- definition of variables
var num_car= 25;
var passenger_per_car= 3;
//calculation of total number of people
var total_passenger= num_car * passenger_per_car
alert(total_passenger);
// end of script -->
</script>
Dynamic Welcome Page AIIT
A script can adapt the content based on
input from the user or other variables
• prompt method of window object
• [Link](“Please enter your
name”, “Lisa”);
OPERATORS AIIT
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Arithmetic AIIT
JavaScript performs arithmetic calculations.
• Arithmetic operators:
• Addition: numberOne + numberTwo
• Subtraction: numberOne – 5
• Multiplication: numberOne * numberTwo
• Division: numberTwo / 6
• Rules of operator precedence
• a*(b–c)
AIIT
<html>
<head>
<script>
function calculate()
{
var a,b,c;
a=[Link]("text1").value;
b=[Link]("text2").value;
c=parseInt(a)+parseInt(b);
[Link]("text3").value=c;
c=a-b;
[Link]("text4").value=c;
c=a*b;
[Link]("text5").value=c;
c=a/b;
[Link]("text6").value=c;
AIIT
</script>
</head>
<body>
<h1>Arithmatic Operation</h1>
Enter the First value<br>
<input type="text" id="text1"><br>
Enter the Second value<br>
<input type="text" id="text2"><br>
Addition<br>
<input type="text" id="text3"><br>
Subtraction<br>
<input type="text" id="text4"><br>
Multiplication<br>
<input type="text" id="text5"><br>
Division<br>
<input type="text" id="text6"><br>
<br><input type="button" value="Calculate" onclick="calculate()"><br>
</body>
</html>
AIIT
Operators and expressions
– +, -, /, % (arithmetic)
– >, <, >=, lt=, ==, !=
(comparisons)
– &&, ||, ! (boolean)
Cont.. AIIT
• == the numbers or objects or values must be equal
• ! Logical NOT
• || Logical OR
• != the numbers or objects or values must not be equal
• >= number on the right must be less than or equal to
the number on the left
• && Logical AND
Cont.. AIIT
• < number on the right must be greater than or equal to
the number on the left
• <=
• < number on the right must be greater than the number
on the left
• > number on the left must be greater than the number
on the right
Cont.. AIIT
• = assigns the value on the right to the object on the left
• the object on the left = the object on the left + the value
on the right
• this also works when appending strings
• +=
• -= the object on the left = the object on the left - the
value on the right
Cont.. AIIT
• % Modulus - divide the first number by the second and
return the remainder
• * multiplies two numbers
• ++ / -- Increment / Decrement a number
Cont.. AIIT
• / divides the first number by the second
• - subtracts the second number from the first
• adds two numbers or appends two strings. If more than
one type of
• variable is appended, including a string appended to a
number or viceversa,
• the result will be a string
Adding Integers AIIT
Prompt user for two integers and
calculate the sum parseInt method
• Converts its string argument to an integer
• Assignment statement
• sum = number1 + number2;
• If user types a non-integer value or clicks Cancel button,
a runtime logic error will occur.
• NaN (not a number): “The sum is NaN”
Display Floating Point Number AIIT
toFixed() function
• Example: var number = 2;
[Link](“[Link]
Fixed(2)</h1>”;
• Result: 2.00
Dialog box AIIT
• JavaScript supports three important types of dialog
boxes.
• These are:
▪Alert dialog box
▪Confirmation Dialog Box
▪Prompt Dialog Box
• 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 AIIT
An alert dialog box is mostly used to
give a warning message to the users.
Like if one input field requires to enter
some text but user does not enter that
field then as a part of validation
Alert Dialog Box AIIT
• 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.
AIIT
• Syntax
[Link]("sometext");
(Note: The [Link]() method can be
written without the window prefix.)
• Example
<html>
<head>
<script type="text/javascript">
<!-- function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!"); } //-->
</script> </head>
<body> <p>Click the following button to see the result: </p>
<input type="button" value="Click Me" onclick="Warn();" />
</body>
</html>
Confirmation Dialog Box AIIT
• A confirmation dialog box is mostly used to take user's
consent on any option. It displays a dialog box with two
buttons: Cancel,OK.
• 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.
Example AIIT
<script type="text/javascript">
<!--
var a = confirm("Do you want to continue ?");
if( a == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
AIIT
• Syntax
[Link]("sometext");
(The [Link]() method can be written without the window
prefix.)
• Example
<html> <head>
<script type="text/javascript">
<!-- function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true )
{ [Link] ("User wants to continue!"); return true; } else
{ [Link] ("User does not want to continue!"); return false; } } //-
->
</script></head>
<body>
<p>Click the following button to see the result: </p>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</body>
</html>
Prompt AIIT
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.
var retVal = prompt("Enter your name : ", "your name
here");
alert("You have entered : " + retVal );
AIIT
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.
AIIT
• Syntax:
[Link]("sometext","defaultText");
(The [Link]() method can be written without the
window prefix.)
• Example
<html>
<head>
<script type="text/javascript">
<!-- function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal); } //-->
</script> </head>
<body> <p>Click the following button to see the result: </p>
<input type="button" value="Click Me" onclick="getValue();" />
</body> </html>
AIIT
Alert dialog box with syntax and
example.
An alert dialog box is mostly used to give a warning message to the users. Like if
one input field requires to enter some text but user does not enter that field then
as a part of validation you can use alert box to give warning message as follows:
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
Alert box gives only
one button "OK" to select and proceed.
Control Structures AIIT
Sequential execution
Three control structures
Sequence structure
Selection structure
if
if…else
switch
Repetition structure
while
do…while
for
If Statement AIIT
• To make use of conditional statements that allow
program to make decisions
• The "If Statement" is a way to make decisions based
on a variable or some other type of data.
If Statement AIIT
• In JavaScript we have the following conditional
statements:
Syntax
• if (condition)
{
code to be executed if condition is true
}
If Statement AIIT
• if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
IF condition AIIT
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
[Link]("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
IF---Else AIIT
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
[Link]("<b>Qualifies for driving</b>");
}
else{
[Link]("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
If---Else If
AIIT
<html>
<body>
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}
else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}
else if( book == "economics" ){
[Link]("<b>Economics Book</b>");
}
else{
[Link]("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
if-else statement AIIT
var rightAnswer = 57;
var num = prompt("Please guess a number below 100:
","");
if (num < rightAnswer)
{
alert("Your guess was too low");
}
Cont.. AIIT
else
if (num > rightAnswer)
{
alert("Your guess was too high");
}
else
{
alert("Congratulations!");
}
else
{
alert("Too bad!");
}
Example AIIT
<script type="text/javascript">
var red = 5;
var blue = 3;
var match = null;
if (red == blue) {
match = 'equal';
} else {
match = 'unequal';
}
[Link](red + ' and ' + blue + ' are ' + match);
</script>
OUTPUT
5 and 3 are unequal
AIIT
JavaScript Switch Statement
• switch statement is used to select one of many blocks
of code to be executed.
• Multiway branch
• The switch value does not need to a number. It can be
a string.
• The case values can be expressions.
AIIT
JavaScript Switch Statement
Syntax
switch (expression) {
case ';':
case ',':
case '.':
punctuation();
break;
default:
noneOfTheAbove();
}
<html> AIIT
<body>
<script type="text/javascript">
<!--
var grade='A';
[Link]("Entering switch block<br />");
switch (grade)
{
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
JavaScript Switch Example
AIIT
<html>
<head>
<script type="text/javascript">
<!--
var myColor =prompt(“enter the color”);
switch (myColor)
{
case "Blue":
[Link]("Just like the sky!");
break
case "Red":
[Link]("Just like shiraz!");
break
default:
[Link]("Suit yourself
then...");
}
//-->
</script>
</head>
switch case JavaScript
AIIT
<html>
<head>
<script type="text/javascript">
var n=prompt("Enter a number between 1 and 7");
switch (n)
{
case (n="1"):
[Link]("Sunday");
break;
case (n="2"):
[Link]("Monday");
break;
case (n="3"):
[Link]("Tuesday");
break;
case (n="4"):
[Link]("Wednesday");
break;
case (n="5"):
[Link]("Thursday");
AIIT
break;
case (n="6"):
[Link]("Friday");
break;
case (n="7"):
[Link]("Saturday");
break;
default:
[Link]("Invalid Weekday");
break
}
</script>
</head>
</html>
for AIIT
• Iterate through all of the elements of
an array:
for (var i = 0; i < [Link]; i +=
1) {
For Loop AIIT
<html> Starting Loop
<body> Current Count : 0
Current Count : 1
<script type="text/javascript"> Current Count : 2
<!-- Current Count : 3
var count; Current Count : 4
[Link]("Starting Loop" + "<br />"); Current Count : 5
Current Count : 6
for(count = 0; count < 10; count++){ Current Count : 7
[Link]("Current Count : " + count ); Current Count : 8
[Link]("<br />"); Current Count : 9
} Loop stopped!
Set the variable to different
[Link]("Loop stopped!"); value and then try...
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
for loop AIIT
var MAX = 10;
var count;
for (count = MAX; count >= 1; count--)
{
[Link]("Countdown: " + count + "<BR>");
}
Output AIIT
• Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
For Loop AIIT
<script type="text/javascript">
<!--
var linebreak = "<br />"; For loop code is beginning
[Link]("For loop code is beginning"); Counter i = 0
Counter i = 1
[Link](linebreak); Counter i = 2
Counter i = 3
for(i = 0; i < 5; i++){ Counter i = 4
For loop code is finished!
[Link]("Counter i = " + i);
[Link](linebreak);
}
[Link]("For loop code is finished!");
</script>
WHILE
AIIT
<html>
Starting Loop
<body>
Current Count : 0
Current Count : 1
<script type="text/javascript">
Current Count : 2
<!--
Current Count : 3
var count = 0;
Current Count : 4
[Link]("Starting Loop ");
Current Count : 5
Current Count : 6
while (count < 10){
Current Count : 7
[Link]("Current Count : " + count + "<br />");
Current Count : 8
count++;
Current Count : 9
}
Loop stopped!
[Link]("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
WHILE LOOP AIIT
<script type="text/javascript">
<!-- While loop is beginning
var myCounter = 0; myCounter = 0
var linebreak = "<br />"; myCounter = 1
[Link]("While loop is beginning"); myCounter = 2
[Link](linebreak); myCounter = 3
myCounter = 4
while(myCounter < 10){ myCounter = 5
[Link]("myCounter = " + myCounter = 6
myCounter); myCounter = 7
[Link](linebreak); myCounter = 8
myCounter++; myCounter = 9
} While loop is finished!
[Link]("While loop is finished!");
</script>
WHILE LOOP AIIT
Adds up numbers until it sees 0
<script>
var sum = 0
var num
num = prompt("Enter new value, or 0
to end")
while (num != 0) {
sum = sum + parseInt(num)
num = prompt("Enter new value, or
0 to end")
}
alert("Sum = " + sum)
</script>
Do..WHILE AIIT
<html> Starting Loop
<body> Current Count : 0
Current Count : 1
<script type="text/javascript"> Current Count : 2
<!-- Current Count : 3
var count = 0; Current Count : 4
Loop Stopped!
[Link]("Starting Loop" + "<br />");
do{
[Link]("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
[Link] ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
AIIT
Computes area of circle until no input
<script>
var rad, area;
rad = prompt("Enter radius")
while (rad != null) {
area = 3.14 * rad * rad
alert("radius = " + rad + ", area = " + area)
[Link]("<br> radius = " + rad + ",
area = " + area)
rad = prompt("Enter radius")
}
</script>
radius = , area = 0
radius = , area = 0
radius = , area = 0
Functions AIIT
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. You can divide your
big programs in a number of small and
manageable functions.
Function AIIT
Function is a group of reusable code which can be called
anywhere in your programme. This eliminates the need of
writing same code again and again. This will help
programmers to write modular code. You can divide your big
programme in a number of small and manageable functions.
Like any other advance programming language, JavaScript
also supports all the features necessary to write modular code
using functions. You must have seen functions like alert()
and write(). We are using these functions again and again but
they have been written in core JavaScript only once.
JavaScript allows us to write our own function
AIIT
<script type="text/javascript"> <script type="text/javascript">
<!-- <!--
function functionname(parameter-list) function sayHello()
{ {
statements alert("Hello there");
} }
//--> //-->
</script> </script>
Function AIIT
• A function contains code that will be executed by an
event or by a call to the function
• Functions can be defined both in the <head> and in
the <body> section of a document. However, to assure
that a function is read/loaded by the browser before it
is called, it could be wise to put functions in the
<head> section.
Functions AIIT
JavaScript instructions are usually grouped
together in a function:
• <script language=“javascript”>
• function myFunction(parameters) {
• // some logical grouping of code
• }
• </script>
• Like a method, procedure, or subroutine.
• Functions are called by events
Syntax AIIT
• function functionname(var1,var2,...,varX)
{
some code
}
• The parameters var1, var2, etc. are variables or values
passed into the function. The { and the } defines the
start and end of the function.
Example AIIT
<html>
<head>
<script language=“javascript”>
function funct() {
// code
}
</script>
</head>
<body>
<input type=button onClick=“funct()”>
</body>
</html>
Example AIIT
• <html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<input type="button" value="Click me!"
onclick="displaymessage()" />
</body>
</html>
Functions with Parameters
AIIT
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
[Link] (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>
AIIT
The onClick() event, with a hyperlink:
<script>
<A HREF="[Link]"
onClick="alert('Thanks for clicking'); return
true;">Click for a test</A><P>
</script>
onsubmit event AIIT
Another most important event type is onsubmit. This
event occurs when you try to submit a form. So you can
put your form validation against this event type.
Here is simple example showing its usage by 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.
AIIT
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="[Link]" onsubmit
=“validation()">
<input type="submit" value="Submit" />
</form>
</body>
</html>
AIIT
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.
AIIT
<html>
<head>
<script type="text/javascript">
<!--
function over() {
alert("Mouse Over");
}
function out() {
alert("Mouse Out");
}
//-->
</script></head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body></html>
AIIT
Computes area of circle using function
<script>
var rad;
do {
rad = prompt("Enter radius")
if (rad == "" || rad == null)
break
alert("radius = " + rad + ", area = " + area(rad))
} while (rad != "" && rad != null)
function area(r) {
return 3.141592654 * r * r
}
</script>
[Link]: print i,i**2 up to n AIIT
<script>
var n = prompt("Enter number")
while (n != null) {
i=0
while (i <= n) {
[Link]("<br>" + i + " " + i*i)
i=i+1
}
n = prompt("Enter number")
}
</script>
Finds first name alphabetically AIIT
(terminate by "" or 0)
<script>
var first
var name
first = name = prompt("Enter new name, or OK to end")
while (name != "" && name != null) {
if (name < first)
first = name
name = prompt("Enter new name, or OK to end")
}
[Link]("
First name alphabetically = " + first)
</script>
First name alphabetically =
concatenates 2 names AIIT
script>
var firstname, secondname,
result
firstname = prompt("Enter first
name")
secondname = prompt("Enter last
name")
result = firstname + secondname
// + means "join" here
alert("hello, " + result)
</script>
AIIT
Find maximum number until it sees 0
<script>
var max = 0
var num
num = prompt("Enter new value, or 0 to end")
while (num != 0) {
if (parseFloat(num) > max)
max = num
num = prompt("Enter new value, or 0 to
end")
}
[Link]("<P> Max = " + max)
</script>
Fibonacci Series AIIT
<html>
<body>
<script type="text/javascript">
var a=0,b=1,c;
[Link]("Fibonacci");
while (b<=10)
{
[Link](c);
[Link]("<br/>");
c=a+b;
a=b;
b=c;
}
</script>
</body>
JavaScript program to check odd or
even numbers with example. AIIT
<html>
<head>
<script type="text/javascript">
var n = prompt("Enter a number to find odd or even", "Type your number here");
n = parseInt(n);
if (isNaN(n))
{
alert("Please Enter a Number");
}
else if (n == 0)
{
alert("The number is zero");
}
else if (n%2)
{
alert("The number is odd");
}
else
{
alert("The number is even");
}
</script> </head><body></body></html>
AIIT
Events AIIT
⚫JavaScript's interaction with HTML is handled
through events that occur when the user or the
browser manipulates a [Link] 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.
⚫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 AIIT
This is the most frequently used event type which
occurs when a user clicks the left button of his
mouse. We can put validation, warning etc.,
against this event type
onclick Event AIIT
This is the most frequently used event type which occurs when a user clicks
mouse left
button. You can put your validation, warning etc against this event type.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button“ onclick="sayHello()" value="Say Hello" />
</body>
</html>
Example AIIT
<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>
Output AIIT
onsubmit Event type AIIT
onsubmit is an event that occurs when we try to
submit a form. we can put form validation against
this event type.
AIIT
<html>
<head>
<script type="text/javascript">
<!--
function over() {
[Link] ("Mouse Over");
}
function out() {
[Link] ("Mouse Out");
} //-->
</script>
</head>
<body>
<p>Bring wer mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
onmouseover and onmouseout AIIT
These two event types will help we create nice
effects with images or even with text as well. The
onmouseover event triggers when we bring
mouse over any element and the onmouseout
triggers when we move mouse out from that
element.
Example AIIT
<html>
<head>
<script type="text/javascript">
<!--
function over() {
[Link] ("Mouse Over");
}
function out() {
[Link] ("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>
Output AIIT
Mouse related events AIIT
⚫ onmousedown :- Triggers when a mouse button is
pressed
⚫ onmousemove :- Triggers when the mouse pointer
moves
⚫ onmouseout :- Triggers when the mouse pointer
moves out of an element
⚫ onmouseover :- Triggers when the mouse pointer
moves over an element
⚫ onmouseup :- Triggers when a mouse button is
released
⚫ onmousewheel :- Triggers when the mouse wheel is
being rotated
AIIT
Some Other Events
⚫ Offline :- Triggers when the document goes offline
⚫ Onabort :- Triggers on an abort event
⚫ onafterprint :- Triggers after the document is printed
⚫ onbeforeonload :- Triggers before the document loads
⚫ onbeforeprint :- Triggers before the document is printed
⚫ onblur :- Triggers when the window loses focus
⚫ oncanplay :- Triggers when media can start play, but might
has to stop for buffering
⚫ oncanplaythrough :- Triggers when media can be
played to the end, without stopping for buffering
⚫ onchange :- Triggers when an element changes
AIIT
Some Other Events
⚫ onclick :- Triggers on a mouse click
⚫ oncontextmenu :- Triggers when a context menu is triggered
⚫ ondblclick :- Triggers on a mouse double-click
⚫ ondrag :- Triggers when an element is dragged
⚫ ondragend :- Triggers at the end of a drag operation
⚫ ondragenter :- Triggers when an element has been dragged to a
valid drop target
⚫ ondragleave :- Triggers when an element is being dragged over a
valid drop target
⚫ ondragover :- Triggers at the start of a drag operation
⚫ ondragstart :- Triggers at the start of a drag operation
⚫ ondrop :- Triggers when dragged element is being dropped
⚫ ondurationchange :- Triggers when the length of the media is
changed
⚫ onemptied :- Triggers when a media resource element suddenly
becomes empty.
AIIT
String Methods
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given
index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
localeCompare() Returns a number indicating whether a reference string comes before or after
or is the same as the given string in sort order.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
130
AIIT
• search()Executes the search for a match between a regular expression and a
specified string.
• slice()Extracts a section of a string and returns a new string.
• split()Splits a String object into an array of strings by separating the string into
substrings.
• substr()Returns the characters in a string beginning at the specified location through
the specified number of characters.
• substring()Returns the characters in a string between two indexes into the string.
• toLocaleLowerCase()The characters within a string are converted to lower case
while respecting the current locale.
• toLocaleUpperCase()The characters within a string are converted to upper case
while respecting the current locale.
• toLowerCase()Returns the calling string value converted to lower case.
• toString()Returns a string representing the specified object.
• toUpperCase()Returns the calling string value converted to uppercase.
• valueOf()Returns the primitive value of the specified object.
131