JavaScript Notes
JavaScript Notes
JavaScript Notes
JAVASCRIPT NOTES
Clocks
Mouse Trailers (an animation that follows your mouse when you surf a site)
Alert Messages
Popup Windows
Page 1
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
What is JavaScript?
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.
Page 2
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Page 3
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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.
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
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
<=
x <= y
true
>=
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 . 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
Page 8
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
\xNN
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.
Page 9
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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.
Page 10
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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>
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
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.
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.
Page 14
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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
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:
do...while - also loops through a block of code while a specified condition is true
Syntax
for (variable=startvalue;variable<endvalue;variable=variable+increment)
{
code to be executed
}
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 />";
}
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++;
}
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);
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:
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!
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>
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.
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
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>
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>
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
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
Page 29
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Page 30
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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
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);
Page 32
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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 />");
Page 33
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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:
Page 35
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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>
Page 36
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
Page 37
Notes for Web Designing & Development on the basis of GGSIPU BCA Syllabus
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
Page 41