Sei sulla pagina 1di 41

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

JAVASCRIPT NOTES

JavaScript is the scripting language of the Web.


JavaScript is used in billions of Web pages to add functionality, validate forms, communicate
with the server, and much more.
JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.
JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in
all browsers since 1996.
The official standardization was adopted by the ECMA organization (an industry standardization
association) in 1997.
JavaScript has been around for several years now, in many different flavors. The main benefit of
Javascript is to add additional interaction between the website and its visitors with just a little
extra work by the web developer. Javascript allows industrious web masters to get more out of
their website than HTML and CSS can provide.
By definition, JavaScript is a client-side scripting language. This means the web surfer's browser
will be running the script. The opposite of client-side is server-side, which occurs in a language
like PHP. PHP scripts are run by the web hosting server.
There are many uses (and abuses!) for the powerful JavaScript language. Here are a few things
that you may or may not have seen in your web surfing days:

Clocks

Mouse Trailers (an animation that follows your mouse when you surf a site)

Drop Down Menus

Alert Messages

Popup Windows

HTML Forms Data Validation

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 1

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

What is JavaScript?

JavaScript was designed to add interactivity to HTML pages

JavaScript is a scripting language

A scripting language is a lightweight programming language

JavaScript is usually embedded directly into HTML pages

JavaScript is an interpreted language (means that scripts execute without preliminary


compilation)

Everyone can use JavaScript without purchasing a license

What Can JavaScript do?

JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML pages

JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element

JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
How To Write JavaScript

1. Use the script tag to tell the browser you are using JavaScript.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 2

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

2. Write or download some JavaScript


3. Test the script!
Your First JavaScript Script
<html>
<body>
<script type="text/JavaScript">
document.write("Hello World!")
</script>
</body>
</html>
Display:
Hello World!
Our first step was to tell the browser we were using a script with the <script> tag. Next we set
the type of script equal to "text/JavaScript". You may notice that doing this is similar to the way
you specify CSS, which is "text/css".
Next, we added an optional HTML comment that surrounds our JavaScript code. If a browser
does not support JavaScript, it will not display our code in plain text to the user! The comment
was ended with a "//-->" because "//" signifies a comment in JavaScript. We add that to prevent a
browser from reading the end of the HTML comment in as a piece of JavaScript code.
JavaScript document.write
The final step of our script was to use a function called document.write, which writes a string
into our HTML document. document.write can be used to write text, HTML, or a little of both.
We passed the famous string of text to the function to spell out "Hello World!" which it printed to
the screen.

Where to Place JavaScript


There are three general areas that JavaScript can be placed for use in a webpage.

Inside the head tag


Within the body tag
In an external file

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 3

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

An Example Head Script


<html>
<head>
<script type="text/JavaScript">
<!-function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

External JavaScript Files


importing an External JavaScript File
Importing an external file is relatively painless. First, the file you are importing must be valid
JavaScript, and only JavaScript. Second, the file must have the file extension ".js". Lastly, you
must know the location of the file.
Let us assume we have a file "myjs.js" that contains a one line Hello World alert function. Also,
let us assume that the file is the same directory as the HTML file we are going to code up. To
import the file you would do the following in your HTML document.
File myjs.js Contents:
function popup() {
alert("Hello World")
}
HTML & JavaScript Code:
<html>
<head>
<script src="myjs.js">
</script>
</head>
<body>
<input type="button" onclick="popup()" value="Click Me!">
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 4

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

</body>
</html>

JavaScript Statements
JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the
browser what to do.
Semicolon ;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written
JavaScript Code Blocks
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements execute together.
An good example of statements grouped together in blocks, are JavaScript functions.
JavaScript is Case Sensitive
JavaScript is case sensitive.
Watch your capitalization closely when you write JavaScript statements:
White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
var name="Hege";
var name = "Hege";
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 5

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming
languages. The definition of an operator is a symbol that is used to perform an operation.

JavaScript Arithmetic Operator Chart


Operator

English

Example

Addition

2+4

Subtraction

6-2

Multiplication

5*3

Division

15 / 3

Modulus

43 % 10

Modulus % may be a new operation to you, but it's just a special way of saying "finding the
remainder

<body>
<script type="text/JavaScript">
<!-var two = 2
var ten = 10
var linebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
document.write(linebreak)
document.write("ten * ten = ")
result = ten * ten
document.write(result)
document.write(linebreak)
document.write("ten / two = ")
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 6

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

result = ten / two


document.write(result)
//-->
</script>
</body>

Comparison Operators
Comparisons are used to check the relationship between variables and/or values. A single equal
sign sets a value while a double equal sign (==) compares two values. Comparison operators are
used inside conditional statements and evaluate to either true or false.

Operator

English

Example

Result

==

Equal To

x == y

false

!=

Not Equal To

x != y

true

<

Less Than

x<y

true

>

Greater Than

x>y

false

<=

Less Than or Equal To

x <= y

true

>=

Greater Than or Equal To

x >= y

false

DATA TYPES
Data can come in many different forms, or what we term types
Some programming languages are strongly typed languages. In these languages, whenever we
use a piece of data we need to explicitly state what sort of data we are dealing with, and use of
that data must follow strict rules applicable to its type. For example, we can't add a number and a
word together.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 7

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

JavaScript, on the other hand, is a weakly typed language and a lot more forgiving about how we
use different types of data. When we deal with data, we often don't need to specify what type of
data it is; JavaScript will work it out for itself.
Numerical Data
Numerical data comes in two forms:

Whole numbers, such as 145, which are also known as integers. These numbers can be
positive or negative and can span a very wide range: 253 to 253.

Fractional numbers, such as 1.234, which are also known as floating-point numbers. Like
integers, they can be positive or negative, and they also have a massive range.

Text Data
Another term for one or more characters of text is a string. We tell JavaScript that text is to be
treated as text and not as code simply by enclosing it inside quote marks ("). For example, "Hello
World" and "A" are examples of strings that JavaScript will recognize. You can also use the
single quote marks (')
JavaScript has a lot of other special characters, which can't be typed in but can be represented
using the escape character in conjunction with other characters to create escape sequences. The
principle behind this is similar to that used in HTML. For example, more than one space in a row
is ignored in HTML, so we represent a space by &nbsp;. Similarly, in JavaScript there are
instances where we can't use a character directly but must use an escape sequence. The following
table details some of the more useful escape sequences:

Escape
Sequences

Character Represented

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Tab

\'

Single quote

\"

Double quote

\\

Backslash

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 8

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

\xNN

NN is a hexadecimal number that identifies a character in the Latin-1


character set.

Boolean Data
The use of yes or no, positive or negative, and true or false is commonplace in the "real" world.
The idea of true and false is also fundamental to digital computers; they don't understand
maybes, only true and false. In fact, the concept of "yes or no" is so useful it has its own data
type in JavaScript: the Boolean data type. The Boolean type has two possible values: true for yes
and false for no.

VariablesStoring Data in Memory


Data can be stored either permanently or temporarily.
We will want to keep important data, such as the details of a person's bank account, in a
permanent store
However, there are other cases where we don't want to permanently store data, but simply want
to keep a temporary note of it.
Each variable is given a name so that you can refer to it elsewhere in your code. These names
must follow certain rules.
Declaring Variables and Giving Them Values
Before you can use a variable, you should declare its existence to the computer using the var
keyword. This warns the computer that it needs to reserve some memory for your data to be
stored in later. To declare a new variable called myFirstVariable you would write
var myFirstVariable;
Note that the semicolon at the end of the line is not part of the variable name, but instead is used
to indicate to JavaScript the end of a statement. This line is an example of a JavaScript statement.
Once declared, a variable can be used to store any type of data.
EXAMPLE
<script>
var a=10,b=20;
document.write(a +"<br>" +b);
</script>

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 9

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

JavaScript Variable Naming Conventions


When choosing a variable name, you must first be sure that you do not use any of the JavaScript
reserved names
Another good practice is choosing variable names that are descriptive of what the variable holds.
If you have a variable that holds the size of a shoe, then name it "shoe_size" to make your
JavaScript more readable.
Finally, JavaScript variable names may not start with a numeral (0-9). These variable names
would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.

What's a Function?
A function is a piece of code that sits dormant until it is referenced or called upon to do its
"function". In addition to controllable execution, functions are also a great time saver for doing
repetitive tasks.
Instead of having to type out the code every time you want something done, you can simply call
the function multiple times to get the same effect. This benefit is also known as "code
reusability".
Example Function in JavaScript
A function that does not execute when a page loads should be placed inside the head of your
HTML document. Creating a function is really quite easy. All you have to do is tell the browser
you're making a function, give the function a name, and then write the JavaScript like normal.

How to Define a Function


Syntax
function functionname()
{
some code
}

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 10

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

HTML & JavaScript Code:


<html>
<head>
<script type="text/javascript">
<!-function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

Calling a Function with Arguments


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

Declare the argument, as variables, when you declare the function:


function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 11

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

Decision MakingThe if and switch Statements


All programming languages allow you to make decisions, that is, they allow the program to
follow a certain course of action depending on whether a particular condition is met. This is what
gives programming languages their intelligence.
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:

if statement - use this statement to execute some code only if a specified condition is true

if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false

if...else if....else statement - use this statement to select one of many blocks of code to be
executed

switch statement - use this statement to select one of many blocks of code to be executed

JavaScript If Statement Syntax


There are two major parts to an If Statement: the conditional statement and the code to be
executed.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 12

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

The conditional statement is a statement that will evaluate to be either True or False. The most
common type of conditional statement used checks to see if something equals a value. An
example would be checking if a date equals your birthday.
<script type="text/javascript">
Var my Num = 7;
if(myNum == 7){
document.write("Lucky 7!");
}
</script>
JavaScript If Statement: Else
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.

The Else clause is executed when the conditional statement is False.


<script type="text/javascript">
var myNum = 10;
if(myNum == 7){
document.write("Lucky 7!");
}else{
document.write("You're not very lucky today...");
}
</script>

If...else if...else Statement


Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 13

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

}
else
{
code to be executed if neither condition1 nor condition2 is true
}

Example
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less
than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening"
greeting:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day

The switch statement is used to perform different action based on different conditions.

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 14

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

execute code block 1


break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically.
Example
Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 15

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

break;
}
The result of x will be:
Today it's Tuesday

The default Keyword


Use the default keyword to specify what to do if there is no match:
Example
If it is NOT Saturday or Sunday, then write a default message:
var day=new Date().getDay();
switch (day)
{
case 6:
x="Today it's Saturday";
break;
case 0:
x="Today it's Sunday";
break;
default:
x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend

LoopingThe for and while Statements

Looping means repeating a block of code while a condition is true. This is achieved in JavaScript
using two statements, the while statement and the for statement.
The JavaScript For Loop resembles the for loop you may have seen in many other programming
languages. It is used when you need to do a set of operations many times, with an increment of
some kind after each run through the block of code.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 16

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal lines in a script we can use loops to perform a task
like this.
In JavaScript, there are different kinds of loops:

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

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

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

for...in - loops through the properties of an object

JavaScript For Loop Explained


There are four important aspects of a JavaScript for loop:
1. The counter variable is something that is created and usually used only in the for loop to
count how many times the for loop has looped. i is the normal label for this counter
variable and what we will be using.
2. The conditional statement. It is what decides whether the for loop continues executing or
not. This check usually includes the counter variable in some way.
3. The counter variable is incremented after every loop in the increment section of the for
loop.
4. The code that is executed for each loop through the for loop.
This may seem strange, but 1-3 all occur on the same line of code. This is because the for loop is
such a standardized programming practice that the designers felt they might as well save some
space and clutter when creating the for loop.

Syntax
for (variable=startvalue;variable<endvalue;variable=variable+increment)
{
code to be executed
}

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 17

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Example
for (i=0; i<5; i++)
{
x=x + "The number is " + i + "<br />";
}
The Break Statement
The break statement breaks the loop and continue executing the code that follows after the loop
(if any).
Example
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br />";
}

The While Loop


While Loops execute a block of code as long as a specified condition is true.
The while loop loops through a block of code while a specified condition is true.
The while loop is an advanced programming technique that allows you to do something over and
over while a conditional statement is true. Although the general uses of the while loop are usually
a bit complex.

javaScript While Loop Explained


There are two key parts to a JavaScript while loop:
1. The conditional statement which must be True for the while loop's code to be executed.
2. The while loop's code that is contained in curly braces "{ and }" will be executed if the
condition is True.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 18

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

When a while loop begins, the JavaScript interpreter checks if the condition statement is true. If
it is, the code between the curly braces is executed. At the end of the code segment "}", the while
loop loops back to the condition statement and begins again.
If the condition statement is always True, then you will never exit the while loop, so be very
careful when using while loops!
Syntax
while (variable<endvalue)
{
code to be executed
}
Note: The < could be any comparing operator.
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i
is less than 5. i will increase by 1 each time the loop runs:
Example
while (i<5)
{
x=x + "The number is " + i + "<br />";
i++;
}

The Do...While Loop


The do...while loop is a variant of the while loop. This loop will execute the block of code once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do
{
code to be executed
}
while (variable<endvalue);

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 19

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Example
The example below uses a do...while loop. The do...while loop will always be executed at least
once, even if the condition is false, because the statements are executed before the condition is
tested:
Example
do
{
x=x + "The number is " + i + "<br />";
i++;
}
while (i<5);

Creating Single Line Comments


To create a single line comment in JavaScript, you place two slashes "//" in front of the code or
text you wish to have the JavaScript interpreter ignore. When you place these two slashes, all
text to the right of them will be ignored, until the next line.
These types of comments are great for commenting out single lines of code and writing small
notes.
JavaScript Code:
<script type="text/javascript">
<!-// This is a single line JavaScript comment
document.write("I have comments in my JavaScript code!");
//document.write("You can't see this!");
//-->
</script>
Display:
I have comments in my JavaScript code!
Creating Multi-line Comments
Although a single line comment is quite useful, it can sometimes be burdensome to use when
disabling long segments of code or inserting long-winded comments. For this large comments
you can use JavaScript's multi-line comment that begins with /* and ends with */.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 20

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

JavaScript Code:
<script type="text/javascript">
<!-document.write("I have multi-line comments!");
/*document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");*/
//-->
</script>
Display:
I have multi-line comments!

JavaScript Array
An array is a variable that can store many variables within it. Many programmers have seen
arrays in other languages, and they aren't that different in JavaScript.
The following points should always be remembered when using arrays in JavaScript:

The array is a special type of variable.

Values are stored into an array by using the array name and by stating the location in the
array you wish to store the value in brackets. Example: myArray[2] = "Hello World";

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

JavaScript has built-in functions for arrays, so check out these built-in array functions
before writing the code yourself!

Creating a JavaScript Array


Creating an array is slightly different from creating a normal variable. Because JavaScript has
variables and properties associated with arrays, you have to use a special function to create a new
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 21

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

array. This example shows how you would create a simple array, store values to it, and access
these values.
JavaScript Code:
<script type="text/javascript">
var myArray = new Array();
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
document.write(myArray[0] + myArray[1] + myArray[2]);
</script>

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When to Use Popups / Alerts
JavaScript alerts are ideal for the following situations:

If you want to be absolutely sure they see a message before doing anything on the
website.

You would like to warn the user about something. For example "the following page
contains humor not suitable for those under the age of 14."

An error has occurred and you want to inform the user of the problem.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 22

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

When asking users for confirmation of some action. For example, if they have just agreed
to sign over the deed to their house and you want to ask them again if they are absolutely
positive they want to go through with this decision!

When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");

Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("I am an alert box!");
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="Show alert box" />
</body>
</html>

Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
The JavaScript confirm function is very similar to the JavaScript alert function. A small dialogue
box pops up and appears in front of the web page currently in focus. The confirm box is different
from the alert box. It supplies the user with a choice; they can either press OK to confirm the
popup's message or they can press cancel and not agree to the popup's request.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 23

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Syntax
confirm("sometext");

Example
<html>
<head>
<script type="text/javascript">
function confirmation() {
var answer = confirm("Leave the document")
if (answer){
alert("Bye bye!")
}
else{
alert("Thanks for sticking around!")
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmation()" value="Leave document">
</form>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
prompt("sometext","defaultvalue");

Example
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 24

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

{
x="Hello " + name + "! How are you today?";
}

Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
alert("Hello\nHow are you?");

Events in JavaScript
What is an Event?
The absolute coolest thing about JavaScript is its ability to help you create dynamic webpages
that increase user interaction, making the visitor feel like the website is almost coming alive right
before her eyes.
JavaScript's interaction with HTML is handled through events that occur when the user or
browser manipulates a page.When the page loads, that is an event. When the user clicks a button,
that click, too, is an event. Another example of events are like pressing any key, closing window,
resizing 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 to occur.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have
a certain set of events which can trigger JavaScript Code.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 25

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Events occur when something in particular happens. For example, the user clicking on the page,
clicking on a hyperlink, or moving his mouse pointer over some text all cause events to occur.
Another example, which is used quite frequently, is the load event for the page.
The building blocks of an interactive web page is the JavaScript event system. An event in
JavaScript is something that happens with or on the webpage. A few example of events:

A mouse click

The webpage loading

Mousing over a hot spot on the webpage, also known as hovering

Selecting an input box in an HTML form

A keystroke

Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
onclick Event :
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.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute
Syntax:
onclick=JavaScript
Example:
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 26

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
</html>

The onmouseover and onmouseout Events


The onmouseover and onmouseout events can be used to trigger a function when the user
mouses over, or out of, an HTML element.
OnMouseOver, as the name suggests, will execute the code when the mouse passes over the link. The
onMouseOver will execute a piece of code when the mouse moves away from the link. They are used in
exactly the same way as onClick.

EXAMPLE
<html>
<head>
<script type="text/javascript">
function popup() {
alert("Hello World")
}
</script></head>
<input type="button" value="Click Me!" onclick="popup()" onmouseover=""
onMouseout="popup()"><br />
</body></html>

The onload and onunload Events


The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
Example
<html>
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 27

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

<body onload="checkCookies()">
<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
{
alert("Cookies are enabled")
}
else
{
alert("Cookies are not enabled")
}
}</script>
<p>An alert box should tell you if your browser has enabled cookies or not.</p>
</body></html>

JavaScript Objects
"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date....
An object is just a special kind of data, with properties and methods. An object is a set of
variables, functions, etc., that encapsulate data and methods.They may have properties and
methods

Properties and Methods


Properties are the values associated with an object.

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 28

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

In the following example we are using the length property of the String object to return the
number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
The output of the code above will be:
12

Methods are the actions that can be performed on objects.


In the following example we are using the toUpperCase() method of the String object to display
a text in uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
The output of the code above will be:
HELLO WORLD!
The String object is used to manipulate a stored piece of text.

Objects in Real Life:


If a car is an object:
The properties of the car include name, model, weight, color, etc.
All cars have these properties, but the values of those properties differ from car to car.
The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods, but they are performed at different times.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 29

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Creating JavaScript Objects


JavaScript has several built-in objects, like String, Date, Array, and more.
You can also create your own objects.

This example creates an object, and adds four properties to it:


Example
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

Using an Object's Properties


Accessing the values contained in an object's properties is very simple. We write the name of the
variable containing (or referencing) our object, followed by a dot, and then the name of the
object's property.
For example, if we defined an Array object contained in the variable myArray, we could access
its length property using
myArray.length
This would give us the number of elements contained in the array.
But what can we do with this property now that we have it? We can use this property as we
would any other piece of data and store it in a variable
var myVariable = myArray.length;
or show it to the user
alert(myArray.length);
In some cases, we can even change the value of the property, such as
myArray.length = 12;
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 30

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Calling an Object's Methods


Methods are very much like functions in that they can be used to perform useful tasks, such as
getting the hours from a particular date or generating a random number for us. Again like
functions, some methods return a value, such as the Date object's getHours() method, while
others perform a task, but return no data, such as the Array object's sort() method.
Using the methods of an object is very similar to using properties in that you put the object's
variable name first, then a dot, and then the name of the method. For example, to sort the
elements of an Array in the variable myArray, you may use the following code:
myArray.sort();
Just like functions, you can pass parameters to some methods, where the parameters are placed
between the parentheses following the method's name. However, whether or not a method takes
parameters, we must still put parentheses after the method's name, just as we did with functions.
As a general rule, anywhere you can use a function, you can use a method of an object.

Types of Object:
1 String Objects
Like most objects, String objects need to be created before they can be used. To create a String
object, we can write
var string1 = new String("Hello");
var string2 = new String(123);
var string3 = new String(123.456);
However, as we have seen, we can also declare a string primitive and use it as if it were a String
object, letting JavaScript do the conversion to an object for us behind the scenes. For example
var string1 = "Hello";

Replace Method

Example for replacing the string


<html>
<body>
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 31

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str="Visit Microsoft";
var n=str.replace("Microsoft","W3Schools");
document.write(n);
}
</script></body></html>
The length Property
The length property simply returns the number of characters in the string. For example
var myName = new String("Paul");
document.write(myName.length);
will write the length of the string "Paul" (that is, 4) to the page.

Substring Method
var myString = "JavaScript";
var mySubString = myString.substring(0,4);
alert(mySubString);

The charAt() and charCodeAt() MethodsSelecting a Single Character from a String


The charAt() method takes one parameter: the index position of the character you want in the
string. It then returns that character. charAt() treats the positions of the string characters as
starting at 0, so the first character is at index 0, the second at index 1, and so on.
For example, to find the last character in a string, we could use the code
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 32

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

var myString = prompt("Enter some text","Hello World!");


var theLastChar = myString.charAt(myString.length - 1);
document.write("The last character is " + theLastChar);

The charCodeAt() method is similar in use to the charAt() method, but instead of returning the
character itself, it returns a number that represents the decimal character code in the Unicode
character set for that character. Recall that computers only understand numbersto the
computer, all our strings are just number data. When we request text rather than numbers, the
computer does a conversion based on its internal understanding of each number and provides the
respective character.
For example, to find the character code of the first character in a string, we could write
var myString = prompt("Enter some text","Hello World!");
var theFirstCharCode = myString.charCodeAt(0);
document.write("The first character code is " + theFirstCharCode);
The indexOf() and lastIndexOf() MethodsFinding a String Inside Another String
<script language="JavaScript" type="text/javascript">
var myString = "Hello paul. How are you Paul";
var foundAtPosition;
foundAtPosition = myString.indexOf("Paul");
alert(foundAtPosition);
</script>
The match() Method
The match() method is very similar to the search() method, except that instead of returning the
position where a match was found, it returns an array. Each element of the array contains the text
of each match that is found.
Example:
<html><body><script>
var str="Hello world!";
document.write(str.match("world") + "<br />");
document.write(str.match("World") + "<br />");

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 33

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

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


document.write(str.match("world!"));
</script></body></html>

2) Math Object
The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math
as an object without creating it.

Mathematical Constants
JavaScript provides eight mathematical constants that can be accessed from the Math object.
These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2
log of E, and base-10 log of E.
You may reference these constants from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods
In addition to the mathematical constants that can be accessed from the Math object there are
also several methods available.
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 34

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Example:
<script>
Var a=10,b=20,c=5,d=2.1,e=2.8;
document.write(Math.abs(e));
document.write("<br>");
document.write(Math.round(e));
document.write("<br>");
document.write(Math.random());
document.write("<br>");
document.write(Math.max(e,d));
document.write("<br>");
document.write(Math.min(e,d));
</script>

3) Date object
The Date object is used to work with dates and times. The Date object is useful when you want
to display a date or use a timestamp in some sort of calculation. In Java, you can either make a
Date object by supplying the date of your choice, or you can let JavaScript create a Date object
based on your visitor's system clock. It is usually best to let JavaScript simply use the system
clock.
Get the JavaScript Time
The Date object has been created, and now we have a variable that holds the current date! To get
the information we need to print out, we have to utilize some or all of the following functions:

getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 35

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

getSeconds() - Number of seconds (0-59)

getMinutes() - Number of minutes (0-59)

getHours() - Number of hours (0-23)

getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday

getDate() - Day of the month (0-31)

getMonth() - Number of month (0-11)

getFullYear() - The four digit year (1970-9999)

Example
<script type="text/javascript">
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
</script>

<script type="text/javascript">
<!-var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script>

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 36

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

4) The Window Object


It is the fundamental object in the browser. The window object is supported by all browsers. It
represent the browsers window in which the document appears.
All global JavaScript objects, functions, and variables automatically become members of the
window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object.
Example for opening and closing a window:
<html><head><script>
function openWin()
{
myWindow=window.open("http://www.w3schools.com","_blank","width=200,height=100");
}
function closeWin()
{
myWindow.close();
}
</script></head><body>
<input type="button" value="Open 'myWindow'" onclick="openWin()" />
<input type="button" value="Close 'myWindow'" onclick="closeWin()" />
</body></html>

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 37

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

Example for Window Status:


<html><head>
<script>
window.Status = "Hello and Welcome";
</script></head></html>

5) The screen Object


The screen object property of the window object contains a lot of information about the display
capabilities of the client machine. Its properties include the height and width properties, which
indicate the vertical and horizontal range of the screen in pixels.
Another property of the screen object, which we will be using in an example later, is the
colorDepth property. This tells us the number of bits used for colors on the client's screen
6) The document ObjectThe Page Itself
Along with the window object, the document object is probably one of the most important and
commonly used objects
Setting Colors According to the User's Screen Color Depth
<body>
<a href="a.html">DateFunction</a></body>
<script>
document.bgColor="green";
document.fgColor="red";document.write("Hello world");
document.title="Document Object";
document.linkColor="aqua";
document.alinkColor="pink";
document.vlinkColor="brown";</script>

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 38

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

7) Form Object:
<html><head><script>
function butCheckForm_onclick()
{
var myForm = document.form1;
if (myForm.txtAge.value == "" || myForm.txtName.value == "")
{
alert("Please complete all the form");
if (myForm.txtName.value == "")
{
myForm.txtName.focus();
}
else
{
myForm.txtAge.focus();
}
}
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
}
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 39

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

}
function txtAge_onblur()
{
var txtAge = document.form1.txtAge;
if (isNaN(txtAge.value) == true)
{
alert("Please enter a valid age");
txtAge.focus();
txtAge.select();
}
}
function txtName_onchange()
{
window.status = "Hi " + document.form1.txtName.value;
}
</script>
</head>
<body>
<form name=form1>
Please enter the following details:
<p>
Name:
By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 40

Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus

<br>
<input type="text" name=txtName onchange="txtName_onchange()">
<br>
Age:
<br>
<input type="text" name=txtAge onblur="txtAge_onblur()" size=3 maxlength=3>
<br>
<input type="button" value="Check Details" name=butCheckForm
onclick="butCheckForm_onclick()">
</form></body></html>

END

By Savleen Kaur, Assistant Professor IITM-JP, GGSIPU New Delhi

Page 41

Potrebbero piacerti anche