0% found this document useful (0 votes)
12 views

Javascript 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Javascript 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 119

JAVASCRIPT

WHY STUDY JAVASCRIPT?

• JAVASCRIPT IS ONE OF THE 3 LANGUAGES ALL WEB DEVELOPERS MUST LEARN:


• 1. HTML TO DEFINE THE CONTENT OF WEB PAGES
• 2. CSS TO SPECIFY THE LAYOUT OF WEB PAGES
• 3. JAVASCRIPT TO PROGRAM THE BEHAVIOR OF WEB PAGES
INTRODUCTION

• JAVASCRIPT IS A LIGHTWEIGHT, INTERPRETED PROGRAMMING LANGUAGE.


• IT IS DESIGNED FOR CREATING NETWORK-CENTRIC APPLICATIONS.
• IT IS COMPLIMENTARY TO AND INTEGRATED WITH JAVA.
• JAVASCRIPT IS VERY EASY TO IMPLEMENT BECAUSE IT IS INTEGRATED WITH HTML.
• IT IS OPEN AND CROSS-PLATFORM.
WHAT IS JAVASCRIPT ?

• JAVASCRIPT IS A DYNAMIC COMPUTER PROGRAMMING LANGUAGE.


• IT IS LIGHTWEIGHT AND MOST COMMONLY USED AS A PART OF WEB PAGES, WHOSE
IMPLEMENTATIONS ALLOW CLIENT-SIDE SCRIPT TO INTERACT WITH THE USER AND MAKE
DYNAMIC PAGES.
• IT IS AN INTERPRETED PROGRAMMING LANGUAGE WITH OBJECT-ORIENTED CAPABILITIES.
• JAVASCRIPT WAS FIRST KNOWN AS LIVESCRIPT, BUT NETSCAPE CHANGED ITS NAME TO
JAVASCRIPT, POSSIBLY BECAUSE OF THE EXCITEMENT BEING GENERATED BY JAVA.
• JAVASCRIPT MADE ITS FIRST APPEARANCE IN NETSCAPE 2.0 IN 1995 WITH THE NAME
LIVESCRIPT.
• THE GENERAL-PURPOSE CORE OF THE LANGUAGE HAS BEEN EMBEDDED IN NETSCAPE,
INTERNET EXPLORER, AND OTHER WEB BROWSERS.
• THE ECMA-262 SPECIFICATION DEFINED A STANDARD VERSION OF THE CORE JAVASCRIPT
LANGUAGE.
1. JAVASCRIPT IS A LIGHTWEIGHT, INTERPRETED PROGRAMMING LANGUAGE.
2. DESIGNED FOR CREATING NETWORK-CENTRIC APPLICATIONS.
3. COMPLEMENTARY TO AND INTEGRATED WITH JAVA.
4. COMPLEMENTARY TO AND INTEGRATED WITH HTML.
5. OPEN AND CROSS-PLATFORM
CLIENT-SIDE JAVASCRIPT

• CLIENT-SIDE JAVASCRIPT IS THE MOST COMMON FORM OF THE LANGUAGE. THE SCRIPT SHOULD
BE INCLUDED IN OR REFERENCED BY AN HTML DOCUMENT FOR THE CODE TO BE INTERPRETED BY
THE BROWSER.
• IT MEANS THAT A WEB PAGE NEED NOT BE A STATIC HTML, BUT CAN INCLUDE PROGRAMS THAT
INTERACT WITH THE USER, CONTROL THE BROWSER, AND DYNAMICALLY CREATE HTML CONTENT.
• THE JAVASCRIPT CLIENT-SIDE MECHANISM PROVIDES MANY ADVANTAGES OVER SERVER-SIDE
SCRIPTS. FOR EXAMPLE, YOU MIGHT USE JAVASCRIPT TO CHECK IF THE USER HAS ENTERED A VALID
E-MAIL ADDRESS IN A FORM FIELD.
• THE JAVASCRIPT CODE IS EXECUTED WHEN THE USER SUBMITS THE FORM, AND ONLY IF ALL THE
ENTRIES ARE VALID, THEY WOULD BE SUBMITTED TO THE WEB SERVER.
• JAVASCRIPT CAN BE USED TO TRAP USER-INITIATED EVENTS SUCH AS BUTTON CLICKS, LINK
NAVIGATION, AND OTHER ACTIONS THAT THE USER INITIATES EXPLICITLY OR IMPLICITLY.
ADVANTAGES OF JAVASCRIPT

• THE MERITS OF USING JAVASCRIPT ARE −

1. 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.
2. IMMEDIATE FEEDBACK TO THE VISITORS − THEY DON'T HAVE TO WAIT FOR A PAGE RELOAD TO SEE IF
THEY HAVE FORGOTTEN TO ENTER SOMETHING.
3. INCREASED INTERACTIVITY − YOU CAN CREATE INTERFACES THAT REACT WHEN THE USER HOVERS OVER
THEM WITH A MOUSE OR ACTIVATES THEM VIA THE KEYBOARD.
4. RICHER INTERFACES − YOU CAN USE JAVASCRIPT TO INCLUDE SUCH ITEMS AS DRAG-AND-DROP
COMPONENTS AND SLIDERS TO GIVE A RICH INTERFACE TO YOUR SITE VISITORS.
LIMITATIONS OF JAVASCRIPT

• WE CANNOT TREAT JAVASCRIPT AS A FULL-FLEDGED PROGRAMMING LANGUAGE. IT LACKS THE


FOLLOWING IMPORTANT FEATURES −
1. CLIENT-SIDE JAVASCRIPT DOES NOT ALLOW THE READING OR WRITING OF FILES. THIS HAS BEEN KEPT
FOR SECURITY REASON.
2. JAVASCRIPT CANNOT BE USED FOR NETWORKING APPLICATIONS BECAUSE THERE IS NO SUCH SUPPORT
AVAILABLE.
3. JAVASCRIPT DOESN'T HAVE ANY MULTITHREADING OR MULTIPROCESSOR CAPABILITIES.
• ONCE AGAIN, JAVASCRIPT IS A LIGHTWEIGHT, INTERPRETED PROGRAMMING LANGUAGE THAT ALLOWS
YOU TO BUILD INTERACTIVITY INTO OTHERWISE STATIC HTML PAGES.
JAVASCRIPT DEVELOPMENT TOOLS

• MICROSOFT FRONTPAGE
• MACROMEDIA DREAMWEAVER MX
• MACROMEDIA HOMESITE 5
SYNTAX

• JAVASCRIPT CAN BE IMPLEMENTED USING JAVASCRIPT STATEMENTS THAT ARE PLACED WITHIN THE <SCRIPT>...
</SCRIPT> HTML TAGS IN A WEB PAGE.
• YOU CAN PLACE THE <SCRIPT> TAGS, CONTAINING YOUR JAVASCRIPT, ANYWHERE WITHIN YOUR WEB PAGE, BUT
IT IS NORMALLY RECOMMENDED THAT YOU SHOULD KEEP IT WITHIN THE <HEAD> TAGS.
• THE <SCRIPT> TAG ALERTS THE BROWSER PROGRAM TO START INTERPRETING ALL THE TEXT BETWEEN THESE
TAGS AS A SCRIPT. A SIMPLE SYNTAX OF YOUR JAVASCRIPT WILL APPEAR AS FOLLOWS.
• <SCRIPT….>

JAVASCRIPT CODE
</SCRIPT>
• THE SCRIPT TAG TAKES TWO IMPORTANT ATTRIBUTES −
1. 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.
2. TYPE − THIS ATTRIBUTE IS WHAT IS NOW RECOMMENDED TO INDICATE THE SCRIPTING
LANGUAGE IN USE AND ITS VALUE SHOULD BE SET TO "TEXT/JAVASCRIPT".
• SO YOUR JAVASCRIPT SEGMENT WILL LOOK LIKE −
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
JAVASCRIPT CODE
</SCRIPT>
FIRST JAVASCRIPT SCRIPT

<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
DOCUMENT.WRITE("HELLO WORLD!")
</SCRIPT>
</BODY>
</HTML>
JAVASCRIPT LITERALS

• THE MOST IMPORTANT RULES FOR WRITING FIXED VALUES ARE:


• NUMBERS ARE WRITTEN WITH OR WITHOUT DECIMALS:
• 10.55
• 125566
• STRINGS ARE TEXT, WRITTEN WITHIN DOUBLE OR SINGLE QUOTES:
• "JOHN DOE"

'JOHN DOE'
• JAVASCRIPT PROGRAMS
1. A COMPUTER PROGRAM IS A LIST OF "INSTRUCTIONS" TO BE "EXECUTED" BY THE COMPUTER.
2. IN A PROGRAMMING LANGUAGE, THESE PROGRAM INSTRUCTIONS ARE CALLED STATEMENTS.
3. JAVASCRIPT IS A PROGRAMMING LANGUAGE.
4. JAVASCRIPT STATEMENTS ARE SEPARATED BY SEMICOLONS:
<BODY><SCRIPT>
VAR X, Y, Z;
X = 5;
Y = 6;
Z = X + Y;
DOCUMENT.WRITE(Z);
</SCRIPT></BODY>
• JAVASCRIPT VARIABLES
1. IN A PROGRAMMING LANGUAGE, VARIABLES ARE USED TO STORE DATA VALUES.
2. JAVASCRIPT USES THE VAR KEYWORD TO DECLARE VARIABLES.
3. AN EQUAL SIGN IS USED TO ASSIGN VALUES TO VARIABLES.
4. IN THIS EXAMPLE, X IS DEFINED AS A VARIABLE. THEN, X IS ASSIGNED (GIVEN) THE VALUE 6:
VAR X;

X = 6;
• JAVASCRIPT OPERATORS
1. JAVASCRIPT USES ARITHMETIC OPERATORS ( + - * / ) TO COMPUTE VALUES:
(5 + 6) * 10
2. JAVASCRIPT USES AN ASSIGNMENT OPERATOR ( = ) TO ASSIGN VALUES TO VARIABLES:
VAR X, Y;
X = 5;
Y = 6;
JAVASCRIPT EXPRESSIONS

• AN EXPRESSION IS A COMBINATION OF VALUES, VARIABLES, AND OPERATORS, WHICH COMPUTES TO A VALUE.


• THE COMPUTATION IS CALLED AN EVALUATION.
• FOR EXAMPLE, 5 * 10 EVALUATES TO 50:

<HTML>
<HEAD><SCRIPT>
DOCUMENT.WRITE(5*10);
</SCRIPT>
</HEAD>
</HTML>
<HTML>
<HEAD><SCRIPT>
VAR X=10;
DOCUMENT.WRITE(5*10);
DOCUMENT.WRITE(X*10);
</SCRIPT>
</HEAD>
</HTML>
<HTML>
<BODY>
<H1>JAVASCRIPT EXPRESSIONS</H1>
<P>EXPRESSIONS COMPUTE TO VALUES.</P>
<P ID="DEMO"></P>
<SCRIPT>
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML = "JOHN" + " " + "DOE";
</SCRIPT>
</BODY>
</HTML>
JAVASCRIPT KEYWORDS

<HTML>
<BODY>
<H1>THE VAR KEYWORD CREATES VARIABLES</H1>
<SCRIPT>
VAR X, Y;
X = 5 + 6;
Y = X * 10;
DOCUMENT.WRITE(Y);
</SCRIPT>
</BODY>
</HTML>
CASE SENSITIVITY

• JAVASCRIPT IS A CASE-SENSITIVE LANGUAGE.


• SO THE IDENTIFIERS TIME AND TIME WILL CONVEY DIFFERENT MEANINGS IN JAVASCRIPT.
• NOTE − CARE SHOULD BE TAKEN WHILE WRITING VARIABLE AND FUNCTION NAMES IN
JAVASCRIPT.
JAVASCRIPT AND CAMEL CASE
 HISTORICALLY, PROGRAMMERS HAVE USED DIFFERENT WAYS OF JOINING MULTIPLE WORDS INTO ONE
VARIABLE NAME:
• HYPHENS:

1. FIRST-NAME, LAST-NAME, MASTER-CARD, INTER-CITY.


2. HYPHENS ARE NOT ALLOWED IN JAVASCRIPT. IT IS RESERVED FOR SUBTRACTIONS.
• UNDERSCORE:

1. FIRST_NAME, LAST_NAME, MASTER_CARD, INTER_CITY.


• UPPER CAMEL CASE (PASCAL CASE):

1. FIRSTNAME, LASTNAME, MASTERCARD, INTERCITY.


• LOWER CAMEL CASE:

1. JAVASCRIPT PROGRAMMERS TEND TO USE CAMEL CASE THAT STARTS WITH A LOWERCASE LETTER:
2. FIRSTNAME, LASTNAME, MASTERCARD, INTERCITY.
JAVASCRIPT STATEMENTS
 IN HTML, JAVASCRIPT STATEMENTS ARE "INSTRUCTIONS" TO BE "EXECUTED" BY THE WEB BROWSER.

• JAVASCRIPT STATEMENTS
1. THIS STATEMENT TELLS THE BROWSER TO WRITE "HELLO DOLLY." INSIDE AN HTML ELEMENT WITH
ID="DEMO":
<HTML><BODY>
<H1>JAVASCRIPT STATEMENTS</H1>
<P>IN HTML, JAVASCRIPT STATEMENTS ARE EXECUTED BY THE BROWSER.</P>
<P ID="DEMO"></P>
<SCRIPT>
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML = "HELLO DOLLY.";
</SCRIPT></BODY></HTML>
• JAVASCRIPT PROGRAMS

1. MOST JAVASCRIPT PROGRAMS CONTAIN MANY JAVASCRIPT STATEMENTS.


2. THE STATEMENTS ARE EXECUTED, ONE BY ONE, IN THE SAME ORDER AS THEY ARE WRITTEN.
3. IN THIS EXAMPLE X, Y, AND Z ARE GIVEN VALUES, AND FINALLY Z IS DISPLAYED:
<BODY><P ID="DEMO"></P>
<SCRIPT>
VAR X, Y, Z;
X = 5;
Y = 6;
Z = X + Y;
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML = Z;
</SCRIPT></BODY>
• SEMICOLONS ;
1. SEMICOLONS SEPARATE JAVASCRIPT STATEMENTS.
2. ADD A SEMICOLON AT THE END OF EACH EXECUTABLE STATEMENT:
VAR A, B, C
A = 5;
B = 6;
C = A + B;
• WHEN SEPARATED BY SEMICOLONS, MULTIPLE STATEMENTS ON ONE LINE ARE ALLOWED:
A = 5; B = 6; C = A + B;

NOTE:ON THE WEB, YOU MIGHT SEE EXAMPLES WITHOUT SEMICOLONS.


ENDING STATEMENTS WITH SEMICOLON IS NOT REQUIRED, BUT HIGHLY
RECOMMENDED.
• JAVASCRIPT WHITE SPACE

1. JAVASCRIPT IGNORES MULTIPLE SPACES. YOU CAN ADD WHITE SPACE TO YOUR SCRIPT TO MAKE IT
MORE READABLE.
2. THE FOLLOWING LINES ARE EQUIVALENT:
• VAR PERSON = "HEGE";
VAR PERSON="HEGE";
 A GOOD PRACTICE IS TO PUT SPACES AROUND OPERATORS ( = + - * / ):

• VAR X = Y + Z;
• JAVASCRIPT LINE LENGTH AND LINE BREAKS
• FOR BEST READABILITY, PROGRAMMERS OFTEN LIKE TO AVOID CODE LINES LONGER THAN 80
CHARACTERS.
• IF A JAVASCRIPT STATEMENT DOES NOT FIT ON ONE LINE, THE BEST PLACE TO BREAK IT, IS AFTER AN
OPERATOR:
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML =
"HELLO DOLLY.";
• JAVASCRIPT CODE BLOCKS
• JAVASCRIPT STATEMENTS CAN BE GROUPED TOGETHER IN CODE BLOCKS, INSIDE CURLY BRACKETS {...}.
• THE PURPOSE OF CODE BLOCKS IS TO DEFINE STATEMENTS TO BE EXECUTED TOGETHER.
• ONE PLACE YOU WILL FIND STATEMENTS GROUPED TOGETHER IN BLOCKS, IS IN JAVASCRIPT FUNCTIONS:
• FUNCTION MYFUNCTION() {
DOCUMENT.GETELEMENTBYID("DEMO1").INNERHTML = "HELLO DOLLY.";
DOCUMENT.GETELEMENTBYID("DEMO2").INNERHTML = "HOW ARE YOU?";
}
• THE <P> ELEMENT SHOULD DO SOMETHING WHEN SOMEONE CLICKS ON IT. TRY TO FIX IT!
• WHEN THE BUTTON IS CLICKED, TRIGGER MYFUNCTION() WITH AN EVENT.
• THE <SPAN> ELEMENT SHOULD DO SOMETHING WHEN SOMEONE MOVES THE MOUSE OVER IT.
TRY TO FIX IT!
<HTML>
<BODY>
<H1>JAVASCRIPT STATEMENTS</H1>
<P>JAVASCRIPT CODE BLOCKS ARE WRITTEN BETWEEN { AND }</P>
<BUTTON TYPE="BUTTON" ONCLICK="MYFUNCTION()">CLICK ME!</BUTTON>
<P ID="DEMO1"></P>
<P ID="DEMO2"></P>
<SCRIPT>
FUNCTION MYFUNCTION() {
DOCUMENT.GETELEMENTBYID("DEMO1").INNERHTML = "HELLO DOLLY.";
DOCUMENT.GETELEMENTBYID("DEMO2").INNERHTML = "HOW ARE YOU?";
}</SCRIPT>
</BODY>
</HTML>
• JAVASCRIPT KEYWORDS
• JAVASCRIPT STATEMENTS OFTEN START WITH A KEYWORD TO IDENTIFY THE JAVASCRIPT ACTION
TO BE PERFORMED.
• HERE IS A LIST OF SOME OF THE KEYWORDS YOU WILL LEARN ABOUT IN THIS TUTORIAL:
• JAVASCRIPT KEYWORDS ARE RESERVED WORDS. RESERVED WORDS CANNOT BE USED AS NAMES
FOR VARIABLES.
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
Stops the execution of JavaScript, and calls (if
debugger
available) the debugging function
Executes a block of statements, and repeats the block,
do ... while
while a condition is true
Marks a block of statements to be executed, as long as
for
a condition is true
function Declares a function
Marks a block of statements to be executed,
if ... else
depending on a condition
return Exits a function
Marks a block of statements to be executed,
switch
depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable
COMMENTS IN JAVASCRIPT

• JAVASCRIPT SUPPORTS BOTH ‘C’ STYLE AND ‘C++’ STYLE COMMENTS, THUS −
• 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 //-->.
EXAMPLE

• <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">

<!--

// THIS IS A COMMENT. IT IS SIMILAR TO COMMENTS IN C++

/*
* THIS IS A MULTILINE COMMENT IN JAVASCRIPT
* IT IS VERY SIMILAR TO COMMENTS IN C PROGRAMMING
*/

//-->
</SCRIPT>
• THERE IS A FLEXIBILITY GIVEN TO INCLUDE JAVASCRIPT CODE ANYWHERE IN AN HTML
DOCUMENT. HOWEVER THE MOST PREFERRED WAYS TO INCLUDE JAVASCRIPT IN AN HTML FILE
ARE AS FOLLOWS −
1. SCRIPT IN <HEAD>...</HEAD> SECTION.
2. SCRIPT IN <BODY>...</BODY> SECTION.
3. SCRIPT IN <BODY>...</BODY> AND <HEAD>...</HEAD> SECTIONS.
• SCRIPT IN AN EXTERNAL FILE AND THEN INCLUDE IN <HEAD>...</HEAD> SECTION.
• IN THE FOLLOWING SECTION, WE WILL SEE HOW WE CAN PLACE JAVASCRIPT IN AN HTML FILE IN
DIFFERENT WAYS.
JAVASCRIPT IN <HEAD>...</HEAD> SECTION

• <HTML> </SCRIPT>

</HEAD>
<HEAD>
<BODY><P>WELCOME</P>
</BODY>
<SCRIPT>

</HTML>
DOCUMENT.WRITE(“HELLOOO!!!”)
JAVASCRIPT IN <BODY>...</BODY> SECTION

• <HTML> DOCUMENT.WRITE("HELLO WORLD")


</SCRIPT>
<HEAD>
</HEAD>
<P>THIS IS WEB PAGE BODY </P>

<BODY>
</BODY>
</HTML>
<SCRIPT>
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section
altogether as follows −

<HTML> <BODY>
<HEAD> <SCRIPT TYPE="TEXT/JAVASCRIPT">
<TITLE>JAVASCRIPT EXAMPLE</TITLE> DOCUMENT.WRITE("EXECUTE DURING PAGE
<SCRIPT TYPE="TEXT/JAVASCRIPT"> LOAD FROM THE BODY<BR>");

DOCUMENT.WRITE("EXECUTE DURING PAGE </SCRIPT>


LOAD FROM THE HEAD<BR>"); </BODY>
</SCRIPT> </HTML>
</HEAD>
FUNCTIONS

• A FUNCTION CONSISTS OF THE FUNCTION KEYWORD FOLLOWED BY THE NAME OF THE


FUNCTION , A SET OF OPEN AND CLOSE PARENTHESES ENCLOSING AN OPTIONAL PARAMETER
LIST AND A BODY ENCLOSED IN A SET OF CURLY BRACES
FUNCTION FUNCTIONNAME(PARAMETERLIST)
{
// BODY
}
A FUNCTION USES THE RETURN KEYWORD TO
RETURN A VALUE FROM A FUNCTION.
<HTML>
<HEAD> <BODY>
<TITLE>JAVASCRIPT EXAMPLE</TITLE> <SCRIPT TYPE="TEXT/JAVASCRIPT">
<SCRIPT TYPE="TEXT/JAVASCRIPT"> DOCUMENT.WRITE(GETHEADER());
FUNCTION GETHEADER() { </SCRIPT>
RETURN "<H1>MAIN HEADING</H1>" </BODY>
} </HTML>
</SCRIPT>
</HEAD>
PARAMETERS ARE SEPARATED BY COMMAS IN
THE FUNCTION DECLARATION.
<HTML> <BODY>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
<TITLE>JAVASCRIPT EXAMPLE</TITLE>
DOCUMENT.WRITE(MULTIPLY(2,4));
<SCRIPT TYPE="TEXT/JAVASCRIPT">
FUNCTION MULTIPLY(NUM1, NUM2) { </SCRIPT>
RETURN NUM1*NUM2; </BODY>
}
</HTML>
</SCRIPT>
</HEAD>
FUNCTIONS.JS FILE

// FUNCTIONS.JS
FUNCTION GETHEADER()
{
RETURN “<H1>MAIN HEADING</H1>“
}
FUNCTION MULTIPLY(NUM1, NUM2) {
RETURN NUM1*NUM2; }
JAVASCRIPT IN EXTERNAL FILE
• HERE IS AN EXAMPLE TO SHOW HOW YOU CAN
INCLUDE AN EXTERNAL JAVASCRIPT FILE IN YOUR
HTML CODE USING SCRIPT TAG AND ITS SRC <BODY>
ATTRIBUTE. <SCRIPT TYPE="TEXT/JAVASCRIPT">
DOCUMENT.WRITE(MULTIPLY(2,4));
<HTML>
</SCRIPT>
<HEAD>
</BODY>
<TITLE>JAVASCRIPT EXAMPLE</TITLE>
</HTML>
<SCRIPT TYPE="TEXT/JAVASCRIPT"
SRC="FUNCTIONS.JS">
</SCRIPT>
</HEAD>
DATATYPES

• JAVASCRIPT ALLOWS YOU TO WORK WITH THREE PRIMITIVE DATA TYPES −

1. NUMBERS, EG. 123, 120.50 ETC.


2. STRINGS OF TEXT E.G. "THIS TEXT STRING" ETC.
3. BOOLEAN E.G. TRUE OR FALSE.
• SYNTAX:

1. VAR LENGTH = 16; // NUMBER


2. VAR LASTNAME = "JOHNSON"; // STRING
3. VAR X = "VOLVO" + 16 + 4;
NUMBER DATATYPE EXAMPLE

<HTML>
<BODY>
<SCRIPT>
VAR X=5;
Y=10;
VAR Z= X+Y;
DOCUMENT.WRITE(Z);
</SCRIPT></BODY></HTML>
<HTML>
<BODY>

<H1>JAVASCRIPT VARIABLES</H1>

<P>IN THIS EXAMPLE, X, Y, AND Z ARE VARIABLES</P>

<P ID="DEMO"></P>

<SCRIPT>
VAR X = 5;
VAR Y = 6;
VAR Z = X + Y;
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML = Z;
</SCRIPT>

</BODY>
</HTML>
JAVA SCRIPT DATA TYPE PROGRAM-1

<HTML>
<BODY>
<SCRIPT>
VAR PI=3.14;
VAR P="JOHN DOE";
VAR ANS= "YES";
DOCUMENT.WRITE(PI);
DOCUMENT.WRITE(P);
DOCUMENT.WRITE(ANS);
</SCRIPT>
</BODY>
</HTML>
JAVA SCRIPT DATA TYPE PROGRAM-2
<SCRIPT>
<HTML>
VAR PI = 3.14;
<BODY> VAR PERSON = "JOHN DOE";
VAR ANSWER = 'YES I AM!';

<H1>JAVASCRIPT VARIABLES</H1>
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML =
PI;
<P>STRINGS ARE WRITTEN WITH //DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML
= PERSON;
QUOTES.</P>
//DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML
<P>NUMBERS ARE WRITTEN WITHOUT = ANSWER;
QUOTES.</P> </SCRIPT>

<P>TRY TO EXPERIMENT BY REMOVING


THE // COMMENTS.</P> </BODY>
• JAVASCRIPT IS UNTYPED LANGUAGE. THIS MEANS THAT A JAVASCRIPT VARIABLE CAN HOLD A
VALUE OF ANY DATA TYPE.
• UNLIKE MANY OTHER LANGUAGES, YOU DON'T HAVE TO TELL JAVASCRIPT DURING VARIABLE
DECLARATION WHAT TYPE OF VALUE THE VARIABLE WILL HOLD.
• THE VALUE TYPE OF A VARIABLE CAN CHANGE DURING THE EXECUTION OF A PROGRAM AND
JAVASCRIPT TAKES CARE OF IT AUTOMATICALLY.
JAVASCRIPT VARIABLE SCOPE

• THE SCOPE OF A VARIABLE IS THE REGION OF YOUR PROGRAM IN WHICH IT IS DEFINED. JAVASCRIPT VARIABLES
HAVE ONLY TWO SCOPES.
1. GLOBAL VARIABLES − A GLOBAL VARIABLE HAS GLOBAL SCOPE WHICH MEANS IT CAN BE DEFINED
ANYWHERE IN YOUR JAVASCRIPT CODE.
2. LOCAL VARIABLES − A LOCAL VARIABLE WILL BE VISIBLE ONLY WITHIN A FUNCTION WHERE IT IS DEFINED.
FUNCTION PARAMETERS ARE ALWAYS LOCAL TO THAT FUNCTION.
WITHIN THE BODY OF A FUNCTION, A LOCAL VARIABLE TAKES PRECEDENCE OVER A GLOBAL VARIABLE WITH THE
SAME NAME. IF YOU DECLARE A LOCAL VARIABLE OR FUNCTION PARAMETER WITH THE SAME NAME AS A
GLOBAL VARIABLE, YOU EFFECTIVELY HIDE THE GLOBAL VARIABLE. TAKE A LOOK INTO THE FOLLOWING EXAMPLE.
LOCAL VARIABLE EXAMPLE

<HTML>
<BODY ONLOAD = MYFUN();>FDGFGDFGDFDDDFDF
<SCRIPT>
VAR CARNAME="GLOBLE"; // DECLARE GLOBLE VARIABLE
FUNCTION MYFUN()
{
VAR CARNAME = "LOCAL"; // DECLARE LOCAL VARIABLE
DOCUMENT.WRITE(CARNAME);
}
</SCRIPT>
</BODY>
</HTML>
GLOBAL VARIABLE EXAMPLE
<HTML>
<BODY>

<P>A GLOBAL VARIABLE CAN BE ACCESSED FROM ANY SCRIPT OR FUNCTION.</P>

<SCRIPT>
VAR CARNAME = "VOLVO";
MYFUNCTION();

FUNCTION MYFUNCTION() {
DOCUMENT.WRITE(CARNAME);
}
</SCRIPT>

</BODY>
</HTML>
JAVASCRIPT VARIABLE NAMES

• WHILE NAMING YOUR VARIABLES IN JAVASCRIPT, KEEP THE FOLLOWING RULES IN MIND.

1. YOU SHOULD NOT USE ANY OF THE JAVASCRIPT RESERVED KEYWORDS AS A VARIABLE NAME. THESE
KEYWORDS ARE MENTIONED IN THE NEXT SECTION. FOR EXAMPLE, BREAK OR BOOLEAN VARIABLE
NAMES ARE NOT VALID.
2. JAVASCRIPT VARIABLE NAMES SHOULD NOT START WITH A NUMERAL (0-9). THEY MUST BEGIN WITH
A LETTER OR AN UNDERSCORE CHARACTER. FOR EXAMPLE, 123TEST IS AN INVALID VARIABLE NAME
BUT _123TEST IS A VALID ONE.
3. JAVASCRIPT VARIABLE NAMES ARE CASE-SENSITIVE. FOR EXAMPLE, NAME AND NAME ARE TWO
DIFFERENT VARIABLES.
WHAT IS AN OPERATOR?

• LET US TAKE A SIMPLE EXPRESSION 4 + 5 IS EQUAL TO 9. HERE 4 AND 5 ARE CALLED OPERANDS AND ‘+’ IS
CALLED THE OPERATOR. JAVASCRIPT SUPPORTS THE FOLLOWING TYPES OF OPERATORS.
1. ARITHMETIC OPERATORS
2. COMPARISION OPERATORS
3. LOGICAL (OR RELATIONAL) OPERATORS
4. ASSIGNMENT OPERATORS
5. CONDITIONAL (OR TERNARY) OPERATORS
• LETS HAVE A LOOK ON ALL OPERATORS ONE BY ONE.
ARITHMETIC OPERATORS
• JAVASCRIPT SUPPORTS THE FOLLOWING ARITHMETIC OPERATORS −
• ASSUME VARIABLE A HOLDS 10 AND VARIABLE B HOLDS 20, THEN −

Sr.No Operator and Description


1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
Sr.No Operator and Description

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
<HTML> DOCUMENT.WRITE("A % B = "); RESULT = A % B;
<BODY> DOCUMENT.WRITE(RESULT);
DOCUMENT.WRITE(LINEBREAK);
<SCRIPT TYPE="TEXT/JAVASCRIPT">
VAR A = 33;
VAR B = 10; DOCUMENT.WRITE("A + B + C = "); RESULT = A + B + C;
DOCUMENT.WRITE(RESULT);
VAR C = "TEST";
DOCUMENT.WRITE(LINEBREAK);
VAR LINEBREAK = "<BR />";
A = A++; DOCUMENT.WRITE("A++ = "); RESULT = A++;
DOCUMENT.WRITE("A + B = ");
DOCUMENT.WRITE(RESULT);
RESULT = A + B; DOCUMENT.WRITE(LINEBREAK);
DOCUMENT.WRITE(RESULT); B = B--; DOCUMENT.WRITE("B-- = "); RESULT = B--;
DOCUMENT.WRITE(LINEBREAK); DOCUMENT.WRITE(RESULT);
DOCUMENT.WRITE("A - B = ");RESULT = A - B; DOCUMENT.WRITE(LINEBREAK);

DOCUMENT.WRITE(RESULT); DOCUMENT.WRITE(LINEBREAK); </SCRIPT>


<P>SET THE VARIABLES TO DIFFERENT VALUES AND
DOCUMENT.WRITE("A / B = "); RESULT = A / B; THEN TRY...</P>
DOCUMENT.WRITE(RESULT); DOCUMENT.WRITE(LINEBREAK); </BODY>
</HTML>
ASSIGNMENT OPERATOR

• ASSIGNMENT OPERATORS ASSIGN VALUES TO


JAVASCRIPT VARIABLES.
• <script> • <script> • <script>
var x = 10; var x = 10; var x = 10;
x += 5; x -= 5; x *= 5;
Document.write(x); Document.write(x); Document.write(x);
</script> </script> </script>

• <script> • <SCRIPT>

var x = 10; VAR X = 10;

x %= 5; X /= 5;

Document.write(x); DOCUMENT.WRITE(X);

</script> </SCRIPT>
<HTML>
DOCUMENT.WRITE("VALUE OF A => (A *= B) => ");
<BODY> RESULT = (A *= B);
DOCUMENT.WRITDOCUMENT.WRITE(LINEBREAK);
<SCRIPT TYPE="TEXT/JAVASCRIPT">
DOCUMENT.WRITE("VALUE OF A => (A *= B) => ");
<!--
RESULT = (A *= B);
VAR A = 33; DOCUMENT.WRITE(RESULT);
DOCUMENT.WRITE(LINEBREAK);
VAR B = 10;

VAR LINEBREAK = "<BR />"; DOCUMENT.WRITE("VALUE OF A => (A /= B) => ");

DOCUMENT.WRITE("VALUE OF A => (A = B) => "); RESULT = (A /= B);


DOCUMENT.WRITE(RESULT);
RESULT = (A = B);
DOCUMENT.WRITE(LINEBREAK);
DOCUMENT.WRITE(RESULT);

DOCUMENT.WRITE(LINEBREAK); DOCUMENT.WRITE("VALUE OF A => (A %= B) => ");


RESULT = (A %= B);
DOCUMENT.WRITE("VALUE OF A => (A += B) => ");
DOCUMENT.WRITE(RESULT);
RESULT = (A += B); DOCUMENT.WRITE(LINEBREAK);
//-->
DOCUMENT.WRITE(RESULT);
</SCRIPT>
DOCUMENT.WRITE(LINEBREAK);
<P>SET THE VARIABLES TO DIFFERENT VALUES AND DIFFERENT OPERATORS AND
DOCUMENT.WRITE("VALUE OF A => (A -= B) => "); THEN TRY...</P>
</BODY>
RESULT = (A -= B);
COMPARISON OPERATOR

• COMPARISON OPERATORS ARE USED IN


LOGICAL STATEMENTS TO DETERMINE
EQUALITY OR DIFFERENCE BETWEEN
VARIABLES OR VALUES.
• GIVEN THAT TABLE EXPLAINS THE
COMPARISON OPERATORS:
EXAMPLE
RESULT = (A > B);
<HTML> DOCUMENT.WRITE(RESULT);
<BODY> DOCUMENT.WRITE(LINEBREAK);
<SCRIPT TYPE="TEXT/JAVASCRIPT"> DOCUMENT.WRITE("(A != B) => ");
VAR A = 10; RESULT = (A != B);
VAR B = 20; DOCUMENT.WRITE(RESULT);
VAR LINEBREAK = "<BR />"; DOCUMENT.WRITE(LINEBREAK);
DOCUMENT.WRITE("(A == B) => "); DOCUMENT.WRITE("(A >= B) => ");
RESULT = (A == B); RESULT = (A >= B);
DOCUMENT.WRITE(RESULT); DOCUMENT.WRITE(RESULT);
DOCUMENT.WRITE(LINEBREAK); DOCUMENT.WRITE(LINEBREAK);
DOCUMENT.WRITE("(A < B) => "); DOCUMENT.WRITE("(A <= B) => ");
RESULT = (A < B); RESULT = (A <= B);
DOCUMENT.WRITE(RESULT); DOCUMENT.WRITE(RESULT);
DOCUMENT.WRITE(LINEBREAK); DOCUMENT.WRITE(LINEBREAK);
DOCUMENT.WRITE("(A > B) => "); </SCRIPT>
LOGİCAL OPERATORS

• LOGICAL OPERATORS ARE USED TO


DETERMINE THE LOGIC BETWEEN VARIABLES
OR VALUES.
<SCRIPT LANGUAGE="JAVASCRIPT">
VAR A = "TANY";
VAR B = "RAMANI";
IF(A == "TANY" && B == "RAMANI")
{
DOCUMENT.WRITE(" LOGICAL OPERATOR AND '&&',
OR '||', NOT '!' ");
}
</SCRIPT>
EXAMPLE
DOCUMENT.WRITE(RESULT);
<HTML>
DOCUMENT.WRITE(LINEBREAK);
<BODY>
DOCUMENT.WRITE("!(A && B) => ");
<SCRIPT TYPE="TEXT/JAVASCRIPT">
RESULT = (!(A && B));
VAR A = TRUE;
DOCUMENT.WRITE(RESULT);
VAR B = FALSE;
DOCUMENT.WRITE(LINEBREAK);
VAR LINEBREAK = "<BR />";
//-->
DOCUMENT.WRITE("(A && B) => ");
</SCRIPT> <P>SET THE VARIABLES TO DIFFERENT
RESULT = (A && B); VALUES AND DIFFERENT OPERATORS AND THEN
DOCUMENT.WRITE(RESULT); TRY...</P>

DOCUMENT.WRITE(LINEBREAK); </BODY>
DOCUMENT.WRITE("(A || B) => "); </HTML>
RESULT = (A || B);
CONDITIONAL OPERATOR – IF STATEMENT
IF STATEMENT
• THE ‘IF’ STATEMENT IS THE FUNDAMENTAL CONTROL STATEMENT THAT ALLOWS JAVASCRIPT TO
MAKE DECISIONS AND EXECUTE STATEMENTS CONDITIONALLY. SYNTAX THE SYNTAX FOR A BASIC
IF STATEMENT IS AS FOLLOWS:
IF (EXPRESSION)
{ STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS TRUE
}
• HERE A JAVASCRIPT EXPRESSION IS EVALUATED.
• IF THE RESULTING VALUE IS TRUE, THE GIVEN STATEMENT(S) ARE EXECUTED.
• IF THE EXPRESSION IS FALSE, THEN NO STATEMENT WOULD BE NOT EXECUTED.
• MOST OF THE TIMES, YOU WILL USE COMPARISON OPERATORS WHILE MAKING DECISIONS
<HTML>
<BODY>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
<!--
VAR AGE = 20;
IF( AGE > 18 ){
DOCUMENT.WRITE("<B>QUALIFIES FOR DRIVING</B>");
}
//-->
</SCRIPT>
<P>SET THE VARIABLE TO DIFFERENT VALUE AND THEN
TRY...</P>
</BODY>
</HTML>
IF...ELSE STATEMENT
• THE ‘IF...ELSE’ STATEMENT IS THE NEXT FORM OF CONTROL STATEMENT THAT ALLOWS JAVASCRIPT
TO EXECUTE STATEMENTS IN A MORE CONTROLLED WAY. SYNTAX THE SYNTAX OF AN IF-ELSE
STATEMENT IS AS FOLLOWS:
IF (EXPRESSION)
{
STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS TRUE
}
ELSE
{
STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS FALSE
}
• HERE JAVASCRIPT EXPRESSION IS EVALUATED.
• IF THE RESULTING VALUE IS TRUE, THE GIVEN STATEMENT(S) IN THE ‘IF’ BLOCK, ARE EXECUTED.
• IF THE EXPRESSION IS FALSE, THEN THE GIVEN STATEMENT(S) IN THE ELSE BLOCK ARE EXECUTED.
<HTML>
<BODY>
<SCRIPT>
VAR AGE = 15;
IF( AGE > 18 ){
DOCUMENT.WRITE("<B>QUALIFIES FOR DRIVING</B>");
}ELSE{
DOCUMENT.WRITE("<B>DOES NOT QUALIFY FOR DRIVING</B>");
}
</SCRIPT>
<P>SET THE VARIABLE TO DIFFERENT VALUE AND THEN TRY...</P>
</BODY>
</HTML>
IF...ELSE IF... STATEMENT
• THE ‘IF...ELSE IF...’ STATEMENT IS AN ADVANCED FORM OF IF…ELSE THAT ALLOWS JAVASCRIPT TO MAKE A CORRECT DECISION OUT OF
SEVERAL CONDITIONS.
• SYNTAX THE SYNTAX OF AN IF-ELSE-IF STATEMENT IS AS FOLLOWS:

IF (EXPRESSION 1){
STATEMENT(S) TO BE EXECUTED IF EXPRESSION 1 IS TRUE
}
ELSE IF (EXPRESSION 2){
STATEMENT(S) TO BE EXECUTED IF EXPRESSION 2 IS TRUE
}
ELSE IF (EXPRESSION 3){
STATEMENT(S) TO BE EXECUTED IF EXPRESSION 3 IS TRUE
}
ELSE
{
• THERE IS NOTHING SPECIAL ABOUT THIS CODE.
• IT IS JUST A SERIES OF IF STATEMENTS, WHERE EACH IF IS A PART OF THE ELSE CLAUSE OF THE
PREVIOUS STATEMENT.
• STATEMENT(S) ARE EXECUTED BASED ON THE TRUE CONDITION, IF NONE OF THE CONDITIONS
IS TRUE, THEN THE ELSE BLOCK IS EXECUTED.
<HTML>
<BODY>
<SCRIPT>
VAR BOOK = "MATHS";
IF( BOOK == "HISTORY" ){
DOCUMENT.WRITE("<B>HISTORY BOOK</B>");
}ELSE IF( BOOK == "MATHS" ){
DOCUMENT.WRITE("<B>MATHS BOOK</B>");
}ELSE IF( BOOK == "ECONOMICS" ){
DOCUMENT.WRITE("<B>ECONOMICS BOOK</B>");
}ELSE{
DOCUMENT.WRITE("<B>UNKNOWN BOOK</B>");
}</SCRIPT>
<P>SET THE VARIABLE TO DIFFERENT VALUE AND THEN TRY...</P>
</BODY>
</HTML>
SWITCH CASE

• YOU CAN USE MULTIPLE IF...ELSE…IF STATEMENTS, AS IN THE PREVIOUS CHAPTER, TO PERFORM
A MULTIWAY BRANCH.
• HOWEVER, THIS IS NOT ALWAYS THE BEST SOLUTION, ESPECIALLY WHEN ALL OF THE BRANCHES
DEPEND ON THE VALUE OF A SINGLE VARIABLE.
• STARTING WITH JAVASCRIPT 1.2, YOU CAN USE A SWITCH STATEMENT WHICH HANDLES
EXACTLY THIS SITUATION, AND IT DOES SO MORE EFFICIENTLY THAN REPEATED IF...ELSE IF
STATEMENTS.
SYNTAX

• THE OBJECTIVE OF A SWITCH STATEMENT IS TO GIVE AN EXPRESSION TO EVALUATE AND


SEVERAL DIFFERENT STATEMENTS TO EXECUTE BASED ON THE VALUE OF THE EXPRESSION. THE
INTERPRETER CHECKS EACH CASE AGAINST THE VALUE OF THE EXPRESSION UNTIL A MATCH IS
FOUND. IF NOTHING MATCHES, A DEFAULT CONDITION WILL BE USED.
SWITCH (EXPRESSION)
{
CASE CONDITION 1: STATEMENT(S)
BREAK;

CASE CONDITION 2: STATEMENT(S)


BREAK;

... CASE CONDITION N: STATEMENT(S)


BREAK;

DEFAULT: STATEMENT(S)
}
• THE BREAK STATEMENTS INDICATE THE END OF A PARTICULAR CASE.
• IF THEY WERE OMITTED, THE INTERPRETER WOULD CONTINUE EXECUTING EACH STATEMENT IN
EACH OF THE FOLLOWING CASES.
<HTML>
<BODY>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
<!--
VAR GRADE='A';
DOCUMENT.WRITE("ENTERING SWITCH BLOCK<BR />");
SWITCH (GRADE)
{
CASE 'A': DOCUMENT.WRITE("GOOD JOB
");
CASE 'B': DOCUMENT.WRITE("PRETTY GOOD");
CASE 'C': DOCUMENT.WRITE("PASSED");
CASE 'D': DOCUMENT.WRITE("NOT SO GOOD");
CASE 'F': DOCUMENT.WRITE("FAILED");
DEFAULT: DOCUMENT.WRITE("UNKNOWN GRADE
")}
DOCUMENT.WRITE("EXITING SWITCH BLOCK");
</SCRIPT>
</BODY>
WHILE LOOP
SYNTAX

• THE SYNTAX OF WHILE LOOP IN JAVASCRIPT IS AS FOLLOWS:


WHILE (EXPRESSION)
{
STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS TRUE
}
<HTML>
<BODY>
<SCRIPT>
VAR COUNT = 0;
DOCUMENT.WRITE("STARTING LOOP ");
WHILE (COUNT < 10){
DOCUMENT.WRITE("CURRENT COUNT : " + COUNT + "<BR />");
COUNT++;
} DOCUMENT.WRITE("LOOP STOPPED!");
//-->
</SCRIPT>
<P>SET THE VARIABLE TO DIFFERENT VALUE AND THEN TRY...</P>
</BODY>
</HTML>
• MAKE THE LOOP START COUNTING FROM 5 INSTEAD OF 0:
• MAKE THE LOOP START COUNTING FROM 5. COUNT UP TO (INCLUDING) 50 AND COUNT ONLY
EVERY FIFTH NUMBER.
• MAKE THE LOOP START COUNTING DOWNWARDS FROM 10 AND STOP AT 1.
• THE OUTPUT SHOULD BE 10 9 8 7 6 5 4 3 2 1 WITH LINE BREAKS.
THE DO...WHILE LOOP

• THE DO...WHILE LOOP IS SIMILAR TO THE


WHILE LOOP EXCEPT THAT THE CONDITION
CHECK HAPPENS AT THE END OF THE LOOP.
THIS MEANS THAT THE LOOP WILL ALWAYS
BE EXECUTED AT LEAST ONCE, EVEN IF THE
CONDITION IS FALSE.
SYNTAX

• THE SYNTAX FOR DO-WHILE LOOP IN JAVASCRIPT IS AS FOLLOWS:


DO{
STATEMENT(S) TO BE EXECUTED; }
WHILE (EXPRESSION);
NOTE: DON’T MISS THE SEMICOLON USED AT THE END OF THE DO...WHILE LOOP.
<HTML>
<BODY>
<SCRIPT>
VAR COUNT = 0;
DOCUMENT.WRITE("STARTING LOOP" + "<BR />");
DO{
DOCUMENT.WRITE("CURRENT COUNT : " + COUNT + "<BR
/>");
COUNT++;
}WHILE (COUNT < 5);
DOCUMENT.WRITE ("LOOP STOPPED!"); </SCRIPT>
<P>SET THE VARIABLE TO DIFFERENT VALUE AND THEN
TRY...</P>
</BODY>
</HTML>
FOR LOOP
• THE ‘FOR’ LOOP IS THE MOST COMPACT FORM OF LOOPING. IT INCLUDES THE FOLLOWING
THREE IMPORTANT PARTS:
1. THE LOOP INITIALIZATION WHERE WE INITIALIZE OUR COUNTER TO A STARTING VALUE. THE
INITIALIZATION STATEMENT IS EXECUTED BEFORE THE LOOP BEGINS.
2. THE TEST STATEMENT WHICH WILL TEST IF A GIVEN CONDITION IS TRUE OR NOT. IF THE
CONDITION IS TRUE, THEN THE CODE GIVEN INSIDE THE LOOP WILL BE EXECUTED, OTHERWISE
THE CONTROL WILL COME OUT OF THE LOOP.
3. THE ITERATION STATEMENT WHERE YOU CAN INCREASE OR DECREASE YOUR COUNTER.
• YOU CAN PUT ALL THE THREE PARTS IN A SINGLE LINE SEPARATED BY SEMICOLONS.
SYNTAX

THE SYNTAX OF FOR LOOP IS JAVASCRIPT IS AS FOLLOWS:


FOR (INITIALIZATION; TEST CONDITION; ITERATION STATEMENT)
{
STATEMENT(S) TO BE EXECUTED IF TEST CONDITION IS TRUE

}
<HTML>
<BODY>
<SCRIPT>
VAR COUNT;
DOCUMENT.WRITE("STARTING LOOP" + "<BR />");
FOR(COUNT = 0; COUNT < 10; COUNT++)
{ DOCUMENT.WRITE("CURRENT COUNT : " + COUNT );
DOCUMENT.WRITE("");
}
DOCUMENT.WRITE("LOOP STOPPED!");
</BODY>
</HTML>
• MAKE THE LOOP START COUNTING FROM 5. COUNT UP TO (INCLUDING) 50, AND COUNT ONLY EVERY
FIFTH NUMBER.
• IN THIS EXERCISE, YOU ARE GOING TO CREATE A FOR LOOP FROM SCRATCH.
WE HAVE ALREADY CREATED THE COUNTER VARIABLE I FOR YOU, AND A TEXT VARIABLE FOR OUTPUT.
YOUR TASK IS TO CREATE A FOR LOOP THAT OUTPUT THE NUMBERS 1 3 5 7 9 WITH LINE BREAKS
BETWEEN EACH NUMBER.
WARNING: REMEMBER TO INCREASE THE VARIABLE USED IN THE CONDITION TO AVOID INFINITE
LOOPS (WILL CRASH YOUR BROWSER).
• MAKE THE LOOP START COUNTING FROM 5 INSTEAD OF 0:
JAVASCRIPT EVENTS

• HTML EVENTS ARE "THINGS" THAT HAPPEN TO HTML ELEMENTS.


• WHEN JAVASCRIPT IS USED IN HTML PAGES, JAVASCRIPT CAN "REACT" ON THESE EVENTS.
• AN HTML EVENT CAN BE SOMETHING THE BROWSER DOES, OR SOMETHING A USER DOES.
• HERE ARE SOME EXAMPLES OF HTML EVENTS:

1. AN HTML WEB PAGE HAS FINISHED LOADING


2. AN HTML INPUT FIELD WAS CHANGED
3. AN HTML BUTTON WAS CLICKED
• OFTEN, WHEN EVENTS HAPPEN, YOU MAY WANT TO DO SOMETHING.
• JAVASCRIPT LETS YOU EXECUTE CODE WHEN EVENTS ARE DETECTED.
• HTML ALLOWS EVENT HANDLER ATTRIBUTES, WITH JAVASCRIPT CODE, TO BE ADDED TO HTML
ELEMENTS.
• WITH SINGLE QUOTES:
<SOME-HTML-ELEMENT SOME-EVENT='SOME JAVASCRIPT'>
• WITH DOUBLE QUOTES:
<SOME-HTML-ELEMENT SOME-EVENT="SOME JAVASCRIPT">
ONCLICK EVENT TYPE

<HTML> <P> CLICK THE FOLLOWING BUTTON AND SEE


<HEAD>
RESULT</P>

<SCRIPT> <INPUT TYPE="BUTTON"


FUNCTION SAYHELLO() { ONCLICK="SAYHELLO()" VALUE="SAY HELLO" />
DOCUMENT.WRITE ("HELLO WORLD") </BODY>
}
</HTML>
</SCRIPT>
</HEAD>
<BODY>
<HTML>
<BODY>

<BUTTON ONCLICK="DOCUMENT.GETELEMENTBYID('DEMO').INNERHTML=DATE()">
THE TIME IS?</BUTTON>

<P ID="DEMO"></P>

</BODY>
</HTML>
<HTML>
<BODY>

<BUTTON ONCLICK="THIS.INNERHTML=DATE()">THE TIME IS?</BUTTON>

</BODY>
</HTML>
<HTML>
<BODY>
<P>CLICK THE BUTTON TO DISPLAY THE DATE.</P>
<BUTTON ONCLICK="DISPLAYDATE()">THE TIME IS?</BUTTON>
<SCRIPT>
FUNCTION DISPLAYDATE() {
DOCUMENT.GETELEMENTBYID("DEMO").INNERHTML = DATE();
}
</SCRIPT>
<P ID="DEMO"></P>
</BODY>
</HTML>
COMMON HTML EVENTS

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Submit Occurs when the user submits an HTML form by
passing the submit button
ONMOUSEOVER AND ONMOUSEOUT

<HTML> </SCRIPT>

<HEAD> </HEAD>

<SCRIPT> <BODY>
<P>BRING YOUR MOUSE INSIDE THE DIVISION TO SEE THE
FUNCTION OVER() {
RESULT:</P>
DOCUMENT.WRITE ("MOUSE OVER");
<DIV ONMOUSEOVER="OVER()" ONMOUSEOUT="OUT()">
} <H2> THIS IS INSIDE THE DIVISION </H2>
FUNCTION OUT() { </DIV>
DOCUMENT.WRITE ("MOUSE OUT"); </BODY>
} </HTML>
• <HTML>
• <BODY>

• <SPAN ONMOUSEOVER="THIS.STYLE.COLOR='RED'">MOUSE OVER ME!</SPAN>

• </BODY>
• </HTML>
JAVASCRİPT FUNCTİONS TO SHOW OUTPUT

• 1)WINDOW.ALERT():
2)WINDOW.STATUS()
3)DOCUMENT.WRITE()
4)DOCUMENT.WRITELN()
ALERT BOX

• ALERT BOX
• AN ALERT BOX İS OFTEN USED İF YOU WANT TO MAKE SURE İNFORMATİON COMES THROUGH TO THE
USER.
• WHEN AN ALERT BOX POPS UP, THE USER WİLL HAVE TO CLİCK "OK" TO PROCEED.

<SCRİPT>
ALERT("HELLO WORLD!")
</SCRİPT>
<SCRIPT>
VAR MYNUM=67;
IF(MYNUM%2==0)
ALERT(“MYNUM+” IS AN EVEN NUM”);
ELSE
ALERT(“MYNUM+” IS AN ODD NUM”);
</SCRIPT>
WINDOW.STATUS():

• THIS FUNCTION SHOW THE MESSAGE IN STATUSBAR . THE MESSAGE TO BE DISPLAYED HAS TO BE PASSED AS
PARAMETER WINDOW.STATUS() .
• <HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
WINDOW.STATUS ="WELCOME TO JAVASCRIPT";
</SCRIPT >
</BODY>
</HTML>
• THE ABOVE CODE DISPLAYS A MESSAGE "WELCOME TO JAVASCRIPT" IN THE STATUS BAR .
DOCUMENT.WRITE():

• THIS FUNCTION PRINT A STRING IN THE CURRENT PAGE. THE MESSAGE TO BE DISPLAYED HAS TO BE
PASSED AS PARAMETER DOCUMENT.WRITE() .
• <HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
DOCUMENT.WRITE( "WELCOME TO JAVASCRIPT");
DOCUMENT.CLOSE();
</SCRIPT >
</BODY>
</HTML>
DOCUMENT.WRITELN():

• THIS FUNCTION WORKS AS THE SAME WAY AS DOCUMENT.WRITE() .


<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
DOCUMENT.WRITELN( "<H3>");
DOCUMENT.WRITELN( "WELCOME TO JAVASCRIPT");
DOCUMENT.WRITE( "</H3>");
</SCRIPT >
</BODY>
</HTML>
DETAILS OF THE INPUT FUNCTIONS

1)WINDOW.PROMPT():
2)WINDOW.CONFIRM() :
1)WINDOW.PROMPT():

• THIS FUNCTION IS USED TO GET ANY VALUE FROM THE USER. THIS FUNCTION TAKES TWO
OPTIONAL PARAMETERS . RETURNS THE VALUE ENTERED BY THE USER IN STRING FORMAT,
HOWEVER IF USER PRESS "CANCEL" RETURNS "NULL"

STRING WINDOW.PROMPT("QUESTION","DEFAULT ANSWER")


EXAMPLE1

• <HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
VAR S;
S = WINDOW.PROMPT("WHAT IS YOUR NAME ?", "YOUR NAME HERE" );
DOCUMENT.WRITELN( S);
</SCRIPT >
</BODY>
</HTML>
EXAMPLE2
<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
VAR NO1,NO2, ANS;
NO1 = WINDOW.PROMPT("GIVE THE FIRST NUMBER ?", "0" ); // GET THE FIRST INPUT
NO2 = WINDOW.PROMPT("GIVE THE SECOND NUMBER ?", "0" ); // GET THE FIRST INPUT
ANS = PARSEFLOAT(NO1) + PARSEFLOAT(NO2);//CONVERT TO FLOAT AND ADD THEM
DOCUMENT.WRITELN( ANS);// PRINT THE ANSWER
</SCRIPT >
</BODY>
</HTML>
• THE ABOVE EXAMPLE TAKES TWO NUMBERS FROM THE USER, CONVERT THEM TO FLOAT USING
PARSEFLOAT(), ADD THEM UP AND SHOW THE ADDED RESULT .
2)WINDOW.CONFIRM() :
• THIS FUNCTION PROMTS THE USER TO CONFIRM THE DECISION. IT SHOWS A MESSAGEBOX WITH TWO BUTTONS "OK" AND "CANCEL" ON IT. IF USER PRESS "OK" IT RETURNS "TRUE" , IF USER
PRESS "CANCEL" IT RETURNS FALSE.

<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
VAR NO1,NO2, ANS;
ANS = WINDOW.CONFIRM("ARE YOU READY?")
IF (ANS==TRUE) // CHECK USERS RESPONSE
DOCUMENT.WRITELN( "START LEARNING JAVASCRIPT");
ELSE
DOCUMENT.WRITELN( "TRY LATER");
</SCRIPT >
</BODY>
</HTML>
FORM VALIDATION
JAVASCRIPT NUMBER VALIDATION
LET'S VALIDATE THE TEXTFIELD FOR NUMERIC VALUE ONLY. HERE, WE ARE USING ISNAN()
<SCRIPT> FUNCTION.
FUNCTION VALIDATE(){

VAR NUM=DOCUMENT.MYFORM.NUM.VALUE;

IF (ISNAN(NUM)){

DOCUMENT.GETELEMENTBYID("NUMLOC").INNERHTML="ENTER NUMERIC VALUE ONLY";

RETURN FALSE;

}ELSE{

RETURN TRUE;

} </SCRIPT>

<FORM NAME="MYFORM" ONSUBMIT="RETURN VALIDATE()" >

NUMBER: <INPUT TYPE="TEXT" NAME="NUM"><SPAN ID="NUMLOC"></SPAN><BR/>

<INPUT TYPE="SUBMIT" VALUE="SUBMIT">

</FORM>
JAVASCRIPT FORM VALIDATION EXAMPLE

<SCRIPT> </SCRIPT>
FUNCTION VALIDATEFORM(){
<BODY>
VAR NAME=DOCUMENT.MYFORM.NAME.VALUE;
<FORM NAME="MYFORM" METHOD="POST" ACTION="
VAR PASSWORD=DOCUMENT.MYFORM.PASSWORD.VALUE;
ABC.JSP" ONSUBMIT="RETURN VALIDATEFORM()" >
IF (NAME==NULL || NAME==""){
NAME: <INPUT TYPE="TEXT" NAME="NAME"><BR/>
ALERT("NAME CAN'T BE BLANK");
PASSWORD: <INPUT TYPE="PASSWORD" NAME="PASSW
RETURN FALSE;
ORD"><BR/>
}ELSE IF(PASSWORD.LENGTH<6){
ALERT("PASSWORD MUST BE AT LEAST 6 CHARACTERS LONG."); <INPUT TYPE="SUBMIT" VALUE="REGISTER">

RETURN FALSE; </FORM>


}
}
JAVASCRIPT RETYPE PASSWORD VALIDATION
<SCRIPT TYPE="TEXT/JAVASCRIPT">

FUNCTION MATCHPASS(){
<FORM NAME="F1" ACTION="REGISTER.JSP" ONSUBMIT="RETURN MATC
VAR FIRSTPASSWORD=DOCUMENT.F1.PASSWORD.VALUE; HPASS()">

VAR SECONDPASSWORD=DOCUMENT.F1.PASSWORD2.VALUE; PASSWORD:<INPUT TYPE="PASSWORD" NAME="PASSWORD" /><BR/>

IF(FIRSTPASSWORD==SECONDPASSWORD){ RE-
ENTER PASSWORD:<INPUT TYPE="PASSWORD" NAME="PASSWORD2"/
RETURN TRUE;
><BR/>
}
<INPUT TYPE="SUBMIT">
ELSE{
</FORM>
ALERT("PASSWORD MUST BE SAME!");

RETURN FALSE;

</SCRIPT>
BASIC HTML
<TR>
<HTML> <TD ALIGN="RIGHT">ZIP CODE</TD>
<HEAD> <TD><INPUT TYPE="TEXT" NAME="ZIP" /></TD>
<TITLE>FORM VALIDATION</TITLE> </TR> <TR>
<SCRIPT TYPE="TEXT/JAVASCRIPT"> <TD ALIGN="RIGHT">COUNTRY</TD>
</SCRIPT> <TD>
</HEAD> <SELECT NAME="COUNTRY">
<BODY> <OPTION VALUE="-1" SELECTED>[CHOOSE YOURS]</OPTION>
<FORM ACTION="/CGI-BIN/TEST.CGI" NAME="MYFORM" ONSUBMIT="RETURN(VALIDATE());"> <OPTION VALUE="1">USA</OPTION>
<TABLE CELLSPACING="2" CELLPADDING="2" BORDER="1"> <OPTION VALUE="2">UK</OPTION>
<TR> <OPTION VALUE="3">INDIA</OPTION>
<TD ALIGN="RIGHT">NAME</TD> </SELECT> </TD> </TR><TR>
<TD><INPUT TYPE="TEXT" NAME="NAME" /></TD> <TD ALIGN="RIGHT"></TD>
</TR> <TD><INPUT TYPE="SUBMIT" VALUE="SUBMIT" /></TD>
<TR> </TR>
<TD ALIGN="RIGHT">EMAIL</TD> </TABLE> </FORM>
<TD><INPUT TYPE="TEXT" NAME="EMAIL" /></TD> </BODY>
</TR> </HTML>
BASIC FORM VALIDATION
IF( DOCUMENT.MYFORM.ZIP.VALUE == "" ||
<SCRIPT TYPE="TEXT/JAVASCRIPT">
ISNAN( DOCUMENT.MYFORM.ZIP.VALUE ) ||
<!-- // FORM VALIDATION CODE WILL COME HERE.
DOCUMENT.MYFORM.ZIP.VALUE.LENGTH != 5 )
FUNCTION VALIDATE()
{
{
ALERT( "PLEASE PROVIDE A ZIP IN THE FORMAT #####." );
IF( DOCUMENT.MYFORM.NAME.VALUE == "" )
DOCUMENT.MYFORM.ZIP.FOCUS() ;
{
RETURN FALSE;
ALERT( "PLEASE PROVIDE YOUR NAME!" );
}
DOCUMENT.MYFORM.NAME.FOCUS() ;
IF( DOCUMENT.MYFORM.COUNTRY.VALUE == "-1" )
RETURN FALSE;
{
}
ALERT( "PLEASE PROVIDE YOUR COUNTRY!" );
IF( DOCUMENT.MYFORM.EMAIL.VALUE == "" )
RETURN FALSE;
{
}
ALERT( "PLEASE PROVIDE YOUR EMAIL!" );
RETURN( TRUE );
DOCUMENT.MYFORM.EMAIL.FOCUS() ;
}
RETURN FALSE;
//-->
}
</SCRIPT>

You might also like