170
Java script

Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Embed Size (px)

Citation preview

Page 1: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Java script

Page 2: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

• 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.

• What is JavaScript?• JavaScript is a scripting language• JavaScript is usually embedded directly into HTML

pages• JavaScript was designed to add interactivity to HTML

pages• JavaScript is an interpreted language (means that

scripts execute without preliminary compilation)• Everyone can use JavaScript without purchasing a

license

Page 3: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

History of JAVA Script:

• Java Script was created by Netscape.• In the past times- people used to call it as Live

Script. But after that because of Java –which of Sun Micro Systems popularity it was called as Java Script, both are nowhere related.

• Microsoft version of Java script is called as Jscript.

• Both Netscape and Microsoft have been instrumental in standardizing JavaScript/Jscript by ECMA International as ECMAScript.

Page 4: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

What can a JavaScript do?

• JavaScript gives HTML designers a programming tool - HTML authors 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 put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

• 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

Page 5: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

• 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 create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

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

Page 6: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

• A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.

• The <script> tag alert the browser program to begin interpreting all the text between these tags as a script.

• Syntax:<script> JavaScript code </script>

Page 7: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Attributes:

The script tag takes three important attributes:• language: This attribute specifies what

scripting language you are using. Typically, its value will be javascript.

• type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".

• src- Specifies URL of an external file containing the JavaScript. This argument overrides any JavaScript contained within the body of this <script> element.

Page 8: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

Syntax:

<script language="javascript" type="text/javascript">

JavaScript code</script>

Page 9: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Put a JavaScript into a HTML page• The example below shows how to use JavaSript

to write text on a web page:• The HTML <script> tag is used to insert a

JavaScript into an HTML page.• Example

<html><body><script type="text/javascript">document.write("Hello World!");</script></body></html>

Page 10: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 11: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

The example below shows how to add HTML tags to the JavaScript:

Example<html><body><script type="text/javascript">document.write("<h1>Hello World!</h1>");</script></body></html>

• The document.write command is a standard JavaScript command for writing output to a page.

• JavaScripts in the body section will be executed WHILE the page loads.

• JavaScripts in the head section will be executed when CALLED.

Page 12: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 13: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

• Where to Put the JavaScript JavaScripts in a page will be executed

immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.1.Scripts in <head>2.Scripts in <body>3.Scripts in <head> and <body>

Page 14: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Scripts in <head>• Scripts to be executed when they are called, or when an

event is triggered, go in the head section.• If you place a script in the head section, you will ensure that

the script is loaded before anyone uses it.Example

<html><head><script type="text/javascript">function message(){alert("This alert box was called with the onload event");}</script></head>

<body onload="message()"></body></html>

Page 15: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 16: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Scripts in <body>• Scripts to be executed when the page loads go in the

body section.• If you place a script in the body section, it generates the

content of a page.Example

<html><head></head>

<body>Introduction<script type="text/javascript">document.write("This message is written by JavaScript");</script></body>

</html>

Page 17: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 18: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Scripts in <head> and <body>• You can place an unlimited number of scripts in your

document, so you can have scripts in both the body and the head section.<html><head><script type="text/javascript">....</script></head><body><script type="text/javascript">....</script></body>

Page 19: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript in External File

• The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

<html> <head> <script type="text/javascript“

src="filename.js" ></script> </head> <body> ....... </body> </html>

Page 20: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

filename.js file

function sayHello() { alert("Hello World") }Output:

Page 21: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript DataTypes

• In JavaScript, there are three primary data types, two composite data types, and two special data types.

• The primary (primitive) data types are:1.String2.Number3.BooleanEx:

• Numbers eg. 123, 120.50 etc.• Strings of text e.g. "This text string" etc.• Boolean e.g. true or false.

Page 22: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

The composite (reference) data types are:1.Object2.Array

The special data types are:3.Null4.Undefined

Page 23: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

JavaScript Statements• JavaScript is a sequence of statements to be executed by

the browser.JavaScript is Case Sensitive• Unlike HTML, JavaScript is case sensitive - therefore

watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions

• The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.

• Note: Using semicolons makes it possible to write multiple statements on one line.

Page 24: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

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.• This example will write a heading and two paragraphs to

a web page:Example

<script type="text/javascript">document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>

Page 25: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

JavaScript Blocks• JavaScript statements can be grouped together in blocks.• Blocks start with a left curly bracket {, and ends with a

right curly bracket }.• The purpose of a block is to make the sequence of

statements execute together. • This example will write a heading and two paragraphs to

a web page:Example

<script type="text/javascript">{document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");}</script>

Page 26: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 27: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

JavaScript Comments• Comments can be added to explain the JavaScript, or to

make the code more readable.• Single line comments start with //.• The following example uses single line comments to

explain the code:Example

<script type="text/javascript">// Write a headingdocument.write("<h1>This is a heading</h1>");// Write two paragraphs:document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>

Page 28: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

JavaScript Multi-Line Comments• Multi line comments start with /* and end with */.• The following example uses a multi line comment to

explain the code:Example

<script type="text/javascript">/*The code below will writeone heading and two paragraphs*/document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>

Page 29: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Using Comments at the End of a Line• In the following example the comment is placed

at the end of a code line:Example

<script type="text/javascript">document.write("Hello"); // Write "Hello"document.write(" Dolly!"); // Write " Dolly!"</script>

Page 30: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Page 31: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Variables

• Data can be stored either permanently or temporarily.Before you use a variable in a JavaScript program, you must declare it.

• A variable can be a number, a single character, a string of characters making up a word or sentence, or a value indicating whether something is true or false.

• Variables are declared with the var keyword as follows:

<script type="text/javascript"> <!-- var money; var name; //--> </script>

Page 32: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Variables

1.boolean: The boolean variable is used to record a value of either true or false.Internally this is essentially stored as 1 for true and 0 for false.

Values: true, false2.number:The number variable holds any type of number, either an integer or a real

number. Values: 1, -31, 0.0233.String: The string variable type stores a string of characters, typically making up

either a word or sentence. string variables can also be assigned empty strings.

Values:"Hello World!"4.function: A function is one of the basic building blocks of most programming

languages including JavaScript. Functions provide a way to organize functionality into clean, reusable modules that can be accessed from any other JavaScript to perform specific tasks.

5.object: JavaScript provides a set of predefined objects to which the JavaScript programmer has access. For example the document object refers to the current web page and can be accessed to make changes to the page content.

Values: document, window

Page 33: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

JavaScript Variables• As with algebra, JavaScript variables are

used to hold values or expressions.• A variable can have a short name, like x, or

a more descriptive name, like carname.

Rules for JavaScript variable names:• Variable names are case sensitive (y and Y

are two different variables)• Variable names must begin with a letter or

the underscore character

Page 34: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Declaring (Creating) JavaScript Variables• Creating variables in JavaScript is most often

referred to as "declaring" variables.• You can declare JavaScript variables with the

var statement:var x;var carname;

• After the declaration shown above, the variables are empty (they have no values yet).

• However, you can also assign values to the variables when you declare them:var x=5;var carname="Volvo";

Page 35: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction

Assigning Values to Undeclared JavaScript Variables• If you assign values to variables that have not yet been

declared, the variables will automatically be declared.These statements:x=5;carname="Volvo";

Redeclaring JavaScript Variables• If you redeclare a JavaScript variable, it will not lose its

original value.var x=5;var x;

• After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.

Page 36: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The JavaScript typeof Operator

The flexible nature of JavaScript variable types can lead to confusion as to the particular type of a variable at any given time in a script.

To address this concern JavaScript provides the typeof operator. The typeof operator returns the current variable type of the specified variable.

Ex:var myVariable = 10; document.writeln ( "myVariable = " + typeof myVariable );

myVariable = "Hello"; document.writeln ( "myVariable = " + typeof myVariable );

Page 37: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Output:

• myVariable = number • myVariable = string

Page 38: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Operators

• Arithmetic Operators• Comparision Operators• Logical (or Relational) Operators• Assignment Operators• Conditional (or ternary) Operators

Page 39: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Arithmatic operators

<html> <head> <title>An Addition Program</title>

<script type = "text/javascript">var firstNumber, // first string entered by user

secondNumber, // second string entered by user number1,

number2, sum; // sum of number1 and number2

// read in first number from user as a string firstNumber = window.prompt( "Enter first integer", "0" );

// read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" );

Page 40: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Operators

// convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber );

// add the numbers sum = number1 + number2;

// display the results document.writeln( "<h1>The sum is " + sum +

"</h1>" );</script>

</head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body></html>

Page 41: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Operators

Page 42: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Operators

Page 43: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Operators

Page 44: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Alert Box• An alert box is often used if you want to make sure information

comes through to the user.• When an alert box pops up, the user will have to click "OK" to

proceed.Syntax:alert("yourtext");• The user will need to click "OK" to proceed. Typical use is when you want to make sure information comes

through to the user.

Page 45: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Ex..<html> <head><title>Printing Multiple Lines in a

Dialog Box</title> <script type = "text/javascript"> <!-- window.alert( "Welcome to\nJavaScript\

nProgramming!" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run this script

again.</p> </body></html>

Page 46: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Page 47: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

• Confirm Box A confirm box is often used if you want the user

to verify or accept something.• Syntax:confirm("yourtext");• When a confirm box pops up, the user will have

to click either "OK" or "Cancel" to proceed. • If the user clicks "OK", the box returns true. If

the user clicks "Cancel", the box returns false.

Page 48: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup BoxesExample

<html><head><script type="text/javascript">function show_confirm(){var r=confirm("Press a button");if (r==true)  {  document.write("You pressed OK!");  }else  {  document.write("You pressed Cancel!");  }}</script></head><body><input type="button" onclick="show_confirm()" value="Show confirm box" /></body></html>

Page 49: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Page 50: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Page 51: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Prompt Box• A prompt box is often used if you want the user

to input a value before entering a page.• syntax is: prompt("yourtext","defaultvalue");• 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.

Page 52: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont…

<html > <head> <title>Using Prompt and Alert Boxes</title> <script type = "text/javascript">

var name; // string entered by the user // read the name from the prompt box as a string name = window.prompt( "Please enter your name", "GalAnt" ); document.writeln( "<h1>Hello " + name + ", welcome to JavaScript programming!</h1>" );

</script>

</head>

<body> <p>Click Refresh (or Reload) to run this script again.</p> </body></html>

Page 53: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Page 54: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Introduction-JavaScript Popup Boxes

Page 55: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Control structures

• Conditional Statements 1.if statements 2.if ... else ... statements

• Looping Statements 1.while loops 2.do ... while loops

• switch Statements • label Statements • with Statements

Page 56: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Conditional Statements -if

<html> <head> <title>Using Relational Operators</title> <script type = "text/javascript"> var name; now = new Date(); // current date and time hour = now.getHours(); // current hour (0-23)

// read the name from the prompt box as a string name = window.prompt( "Please enter your name",

"GalAnt" );

Page 57: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Control structures-ifif ( hour < 12 ) document.write( "<h1>Good Morning, " );

// determine whether the time is PM if ( hour >= 12 ) {

hour = hour - 12;

if ( hour < 6 ) document.write( "<h1>Good Afternoon, " );

if ( hour >= 6 ) document.write( "<h1>Good Evening, " ); }

document.writeln( name + ", welcome to JavaScript programming!</h1>" );

</script> </head>

<body> <p>Click Refresh (or Reload) to run this script again.</p> </body></html>

Page 58: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Control structures-if

Page 59: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Control structures-if

Page 60: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Control structures-Switch Statement<script type="text/javascript">

//You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.

var d=new Date();theDay=d.getDay();switch (theDay){case 5:  document.write("Finally Friday");  break;case 6:  document.write("Super Saturday");  break;case 0:  document.write("Sleepy Sunday");  break;default:  document.write("I'm looking forward to this weekend!");}</script>

Page 61: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Loops

for Loop• The for loop is used when you know in advance how

many times the script should run.<html><body><script type="text/javascript">var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}</script></body></html>

Page 62: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Loops

Page 63: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Loops

JavaScript While Loop• oops execute a block of code a specified number of

times, or while a specified condition is true.Example

<html><body><script type="text/javascript">var i=0;while (i<=5)  {  document.write("The number is " + i);  document.write("<br />");  i++;  }</script></body></html>

Page 64: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Loops

The do...while Loop• This loop will execute the block of code ONCE, and then it

will repeat the loop as long as the specified condition is true.

Example<html><body><script type="text/javascript">var i=0;do  {  document.write("The number is " + i);  document.write("<br />");  i++;  }while (i<=5);</script></body></html>

Page 65: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Break

The break Statement• The break statement will break the loop and continue executing the code that

follows after the loop (if any).

<html> <head> <script type = "text/javascript"> <!-- for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) break; // break loop only if count == 5

document.writeln( "Count is: " + count + "<br />" ); }

document.writeln( "Broke out of loop at count = " + count ); // --> </script>

</head><body></body></html>

Page 66: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Break

Page 67: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Continue Statements

The continue Statement• The continue statement will break the current loop and

continue with the next value<html> <head> <script type = "text/javascript">

for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) continue; // skip remaining code in loop // only if count == 5

document.writeln( "Count is: " + count + "<br />" ); } document.writeln( "Used continue to skip printing 5" );</script> </head><body></body></html>

Page 68: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Continue Statements

Page 69: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The labeled continue Statement

<html > <head> <title>Using the continue Statement with a Label</title> <script type = "text/javascript"> nextRow: // target label of continue statement for ( var row = 1; row <= 5; ++row ) { document.writeln( "<br />" ); for ( var column = 1; column <= 10; ++column ) {

if ( column > row ) continue nextRow; // next iteration of labeled loop document.write( "* " ); } }</script> </head><body></body></html>

Page 70: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The labeled continue Statement

Page 71: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The labeled break Statement

<html> <head>

<script type = "text/javascript">stop: { // labeled block

for ( var row = 1; row <= 10; ++row ) { for ( var column = 1; column <= 5 ; ++column ) {

if ( row == 5 ) break stop; // jump to end of stop block

document.write( "* " ); }

document.writeln( "<br />" ); }

// the following line is skipped document.writeln( "This line should not print" ); }

document.writeln( "End of script" );</script>

</head><body></body></html>

Page 72: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The labeled break Statement

Page 73: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The with Keyword:

• The with keyword is used as a kind of shorthand for referencing an object's properties or methods.

• Syntax:with (object){ properties used without the object name and

dot }

Page 74: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

For/in

• Java script provides a for/in construct ,which allows us to iterate through the array elements or properties of an object.

• Syntax:for(loopvariable in object){Code to execute}

Page 75: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Ex:object

<script type=“text/javascript”>var origin=new Object();origin.x=0;origin.y=0;for(i in origin) document.write(i+’=‘+origin[i]);origin.x=2;for(i in origin)document.write(i+’=‘+origin[i]);</script>

Page 76: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Ex:array

<script type=“text/javascript”>var odds=[1,3];odds[4]=9;for(i in odds)document.write(“<br>odds[“+i+”]=odds[i]);</script>

Page 77: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

• A function will be executed by an event or by a call to the function.

• Functions can be defined both in the <head> and in the <body> section of a document.

• Syntax:function function_name(){//java script code}

Page 78: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

1 Declaring and Calling a JavaScript Function2 Passing Arguments to a Function3 Returning a Value from a Function4 Where to Place Function Declarations

Page 79: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

1 Declaring and Calling a JavaScript Function

• The syntax of a JavaScript function is as follows: function ''name'' ( ''argument1'', ''argument2'',

''argument3'' ... ) { ''statements'‘ return ''value'' }

Page 80: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Ex:

<html> <head> <title>A Simple JavaScript Function Example</title> <script language="JavaScript"

type="text/javascript"> function sayHello() { alert("Hello!"); } </script> </head> <body> <script language="JavaScript"

type="text/javascript"> sayHello(); </script> </body> </html>

Page 81: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Passing Arguments to a Function

<html> <head> <title>A Simple JavaScript Function

Example</title> <script language="JavaScript"

type="text/javascript"> function sayHello( day, month) { alert("Hello! Today is the " + day + " of " +

month); } </script> </head> <script language="JavaScript" type="text/javascript"> sayHello( "24th", "July" ); sayHello ( "1st", "August" ); sayHello ( "24th", "May" ); </script> </body> </html>

Page 82: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Returning a Value from a Function

<html> <head> <title>A Simple JavaScript Function Example </title> <script type="text/javascript"> function addValues( value1, value2) { return value1 + value2; } </script> </head> <script type="text/javascript"> var result = addValues( 10, 20) document.write ( "Result = " + result); </script> </body> </html>

Page 83: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

JavaScript Function ExampleExample

<html><head><script type="text/javascript">function displaymessage(){alert("Hello World!");}</script></head>

<body><form><input type="button" value="Click me!" onclick="displaymessage()" /></form></body></html>

Page 84: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

Page 85: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

The return Statement• The return statement is used to specify the value that is

returned from the function.

Example<html><head><script type="text/javascript">function product(a,b){return a*b;}</script></head>

<body><script type="text/javascript">document.write(product(4,3));</script></body></html>

Page 86: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

Page 87: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions-another example

<head> <script type = "text/javascript">

var input1 = window.prompt( "Enter first number", "0" ); var input2 = window.prompt( "Enter second number", "0" ); var input3 = window.prompt( "Enter third number", "0" ); var value1 = parseFloat( input1 ); var value2 = parseFloat( input2 ); var value3 = parseFloat( input3 ); var maxValue = maximum( value1, value2, value3 );

document.writeln( "First number: " + value1 + "<br />Second number: " + value2 + "<br />Third number: " + value3 + "<br />Maximum is: " + maxValue );

Page 88: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

// maximum method definition (called from line 25) function maximum( x, y, z ) { return Math.max( x, Math.max( y, z ) ); }

</script>

</head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body></html>

Page 89: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

Page 90: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions

Page 91: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions - factorial

<html > <head>

<script type = "text/javascript"> document.writeln("<table border = '1' width = '100%'>" ); for ( var i = 0; i <= 10; i++ )

document.writeln( "<tr><td>“+i+"!</td><td>"+ factorial(i )+"</td></tr>" ); document.writeln( "</table>" ); function factorial( number ) { if ( number <= 1 ) // base case return 1; else return number * factorial( number - 1 ); } </script> </head><body></body></html>

Page 92: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions - factorial

Page 93: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions-scope

<html > <head> <title>A Scoping Example</title>

<script type = "text/javascript">var x = 1; // global variable

function start() { var x = 5; // variable local to function start

document.writeln( "local x in start is " + x ); functionA(); // functionA has local x

functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value

document.writeln( "<p>local x in start is " + x + "</p>" ); }

Page 94: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions-scope

function functionA() { var x = 25; // initialized each time document.writeln( "<p>local x in functionA is " + x + " after entering functionA" ); ++x; document.writeln( "<br />local x in functionA is " + x + " before exiting functionA” + "</p>" ); }

function functionB() {document.writeln( "<p>global variable x is " + x + " on entering functionB" ); x *= 10; document.writeln( "<br />global variable x is " + x + " on exiting functionB" + "</p>" ); } </script> </head> <body onload = "start()"></body></html>

Page 95: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Functions-scope

Page 96: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Objects

• JavaScript Objects represent self contained entities consisting of variables (called properties in object terminology) and functions (called methods) that can be used to perform tasks and store complex data.

JavaScript objects fall into three categories:1. Built-in Objects, 2.Custom Objects ,3.Document Object Model (DOM) Objects.

Page 97: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

• Types:

1. Built-in objects are objects that are provided with JavaScript to make your life as a JavaScript developer easier. In many of the examples given in this book we have used the document.write() mechanism to write text to the current web page. Whether you knew it or not, you have been using the write() method of the JavaScript built-in document object when you have run these scripts.

2. Document Object Model (DOM) Objects provide the foundation for creating dynamic web pages. The DOM provides the ability for a JavaScript script to access, manipulate, and extend the content of a web page dynamically (i.e. without having to reload the page). The DOM essentially presents the web page as a tree hierarchy of objects representing the contents and elements of the web page. These objects, in turn, contain properties and methods that allow you to access and change parts of the web page.

3. Custom objects are objects that you, as a JavaScript developer, create and use.

Page 98: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Creating a Custom JavaScript Object

• Creating a custom JavaScript object is quite similar to constructing a function.

The syntax is as follows: function object(''parameter1, parameter2, parameter3,...'') { this.property1 = parameter1; this.property2 = parameter2; this.property3 = parameter3; this.method1 = function1; this.method2 = function2; this.method3 = function3; }

Page 99: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

• Syntax:Creating a Array object:var fruits = new Array( "apple", "orange“); • Array Properties:

Page 100: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Properties:

Page 101: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Methods

Page 102: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Cont..

Page 103: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

An array is a special variable, which can hold more than one value, at a time.

<html> <head> <script type = "text/javascript"> function initializeArrays() { var n1 = new Array( 5 ); // allocate 5-element Array var n2 = new Array(); // allocate empty Array

for ( var i = 0; i < n1.length; ++i ) n1[ i ] = i;

for ( i = 0; i < 5; ++i ) n2[ i ] = i; outputArray( "Array n1 contains", n1 ); outputArray( "Array n2 contains", n2 ); }

Page 104: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\" width =" +

"\"100%\">" ); document.writeln( "<thead><th width = \"100\"" + "align = \"left\">Subscript</th>" + "<th align = \"left\">Value</th></thead><tbody>" ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); document.writeln( "</tbody></table>" ); }</script> </head><body onload = "initializeArrays()"></body></html>

Page 105: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 106: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

<html> <head> <title>Initializing an Array with a Declaration</title> <script type = "text/javascript"> function start() { // Initializer list specifies number of elements and // value for each element. var colors = new Array( "cyan", "magenta", "yellow", "black" );

var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ]; outputArray( "Array colors contains", colors );

outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); }

Page 107: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\"" + "width = \"100%\">" ); document.writeln( "<thead><th width = \"100\" " + "align = \"left\">Subscript</th>" + "<th align = \"left\">Value</th></thead><tbody>" ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); document.writeln( "</tbody></table>" ); }</script> </head><body onload = "start()"></body></html>

Page 108: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 109: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

<html > <head> <title>Initializing Multidimensional Arrays</title>

<script type = "text/javascript">function start()

{ var array1 = [ [ 1, 2, 3 ], // first row [ 4, 5, 6 ] ]; // second row var array2 = [ [ 1, 2 ], // first row [ 3 ], // second row [ 4, 5, 6 ] ]; // third row

outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); }

Page 110: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

function outputArray( header, theArray )

{ document.writeln( "<h2>" + header + "</h2><tt>" ); for ( var i in theArray ) {

for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); document.writeln( "<br />" ); }

}</script>

</head><body onload = "start()"></body></html>

Page 111: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 112: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

<html> <head> <title>Sum the Elements of an Array</title> <script type = "text/javascript">

function start() { var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0, total2 = 0; for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 ); for ( var element in theArray ) total2 += theArray[ element ]; document.writeln( "<br />Total using for...in: " + total2 ); }</script> </head><body onload = "start()"></body></html>

Page 113: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 114: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

<html> <head> <title>Passing Arrays and Individual Array Elements to Functions</title> <script type = "text/javascript"> function start() { var a = [ 1, 2, 3, 4, 5 ]; document.writeln( "<h2>Effects of passing entire " + "array by reference</h2>" ); outputArray( "The values of the original array are: ", a ); modifyArray( a ); // array a passed by reference outputArray( "The values of the modified array are: ", a ); document.writeln( "<h2>Effects of passing array " + "element by value</h2>" +"a[3] before modifyElement: " + a[ 3 ] ); modifyElement( a[ 3 ] ); document.writeln("<br />a[3] after modifyElement: " + a[ 3 ] ); }

Page 115: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

function outputArray( header, theArray ) { document.writeln( header + theArray.join( " " ) + "<br />" ); }function modifyArray( theArray ) { for ( var j in theArray ) theArray[ j ] *= 2; }function modifyElement( e ) { e *= 2; document.writeln( "<br />value in modifyElement: " + e ); } </script></head><body onload = "start()"></body></html>

Page 116: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 117: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

<html > <head> <title>Sorting an Array with Array Method sort</title>

<script type = "text/javascript"> function start() { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];

document.writeln( "<h1>Sorting an Array</h1>" ); outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); // sort the array outputArray( "Data items in ascending order: ", a ); }

Page 118: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

// outputs "header" followed by the contents of "theArray"

function outputArray( header, theArray ) { document.writeln( "<p>" + header + theArray.join( " " ) + "</p>" ); } // comparison function for use with sort function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); }</script>

</head><body onload = "start()"></body></html>

Page 119: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Array Object

Page 120: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

String object

<html > <head> <title>Character Processing Methods</title> <script type = "text/javascript">

var s = "ZEBRA"; var s2 = "AbCdEfG"; document.writeln( "<p>Character at index 0 in '" + s + "' is " + s.charAt( 0 ) ); document.writeln( "<br />Character code at index 0 in '" + s + "' is " + s.charCodeAt( 0 ) + "</p>" ); document.writeln( "<p>'" + String.fromCharCode( 87, 79, 82, 68 ) + "' contains character codes 87, 79, 82 and 68</p>" ) document.writeln( "<p>'" + s2 + "' in lowercase is '" + s2.toLowerCase() + "'" ); document.writeln( "<br />'" + s2 + "' in uppercase is '" + s2.toUpperCase() + "'</p>" ); </script> </head><body></body></html>

Page 121: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

String object

Page 122: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

String object

<html > <head><title>XHTML Markup Methods of the String Object</title> <script type = "text/javascript"> var anchorText = "This is an anchor", blinkText = "This is blinking text", fixedText = "This is monospaced text", linkText = "Click here to go to anchorText", strikeText = "This is strike out text", subText = "subscript“, supText = "superscript"; document.writeln( anchorText.anchor( "top" ) ); document.writeln( "<br />" + blinkText.blink() ); document.writeln( "<br />" + fixedText.fixed() ); document.writeln( "<br />" + strikeText.strike() ); document.writeln("<br />This is text with a " + subText.sub() ); document.writeln( "<br />This is text with a " + supText.sup() ); document.writeln( "<br />" + linkText.link( "#top" ) ); </script> </head><body></body></html>

Page 123: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

String object

Page 124: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Date object

<html > <head><title>Date and Time Methods</title> <script type = "text/javascript"> var current = new Date(); document.writeln( "<h1>String representations and valueOf</h1>" ); document.writeln( "toString: " + current.toString() + "<br />toLocaleString: " + current.toLocaleString() + "<br />toUTCString: " + current.toUTCString() + "<br />valueOf: " + current.valueOf() ); document.writeln("<h1>Get methods for local time zone</h1>" ); document.writeln( "getDate: " + current.getDate() + "<br />getDay: " + current.getDay() + "<br />getMonth: " + current.getMonth() + "<br />getFullYear: " + current.getFullYear() + "<br />getTime: " + current.getTime() + "<br />getHours: " + current.getHours() +

Page 125: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Date object

"<br />getMinutes: " + current.getMinutes() +

"<br />getSeconds: " + current.getSeconds() + "<br />getMilliseconds: " + current.getMilliseconds() + "<br />getTimezoneOffset: " + current.getTimezoneOffset() ); document.writeln( "<h1>Specifying arguments for a new Date</h1>" ); var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 ); document.writeln( "Date: " + anotherDate ); document.writeln("<h1>Set methods for local time zone</h1>" ); anotherDate.setDate( 31 ); anotherDate.setMonth( 11 ); anotherDate.setFullYear( 2001 ); anotherDate.setHours( 23 ); anotherDate.setMinutes( 59 ); anotherDate.setSeconds( 59 ); document.writeln( "Modified date: " + anotherDate );</script> </head><body></body></html>

Page 126: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Date object

Page 127: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Compare Two Dates

• The Date object is also used to compare two dates.• The following example compares today's date with the

14th January 2010:• var myDate=new Date();

myDate.setFullYear(2010,0,14);var today = new Date();

if (myDate>today)  {  alert("Today is before 14th January 2010");  }else  {  alert("Today is after 14th January 2010");  }

Page 128: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document Object Methods

Page 129: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document Object Properties

Page 130: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Using the JavaScript Document Object

• Writing text to a document The document object open() and write()

methods can be used to dynamically write text to a web page.

Ex:<html> <head> <title>JavaScript Document

Object Example</title> </head> <body> <p> This is a line of text specified in the HTML file </p> <script language="javascript" type="text/javascript"> document.open() document.write("This is a line of text written to the document using JavaScript"); </script> </body> </html>

Page 131: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Writing Text to a document in a different Window

• <html> • <head> <title>JavaScript Document Object

Example</title> <script language="javascript" type="text/javascript"> function writeContent(content, windowObj) { windowObj.document.write(content); } </script> </head> <body> <script language="javascript" type="text/javascript"> newWindowObj = window.open ("", "MyWindow"); </script> <form action=""> <input type=button value="Write to New Window" onclick="writeContent('This is new content in the new window', newWindowObj)"/> </form> </body> </html>

Page 132: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document object

<html > <head> <title>Using Cookies</title> <script type = "text/javascript"> var now = new Date(); // current date and time var hour = now.getHours(); // current hour (0-23) var name; if ( hour < 12 ) // determine whether it is morning document.write( "<h1>Good Morning, " ); else { hour = hour - 12; // convert from 24 hour clock to PM time // determine whether it is afternoon or evening if ( hour < 6 ) document.write( "<h1>Good Afternoon, " ); else document.write( "<h1>Good Evening, " ); }

Page 133: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document object

// determine whether there is a cookie if ( document.cookie ) {// convert escape characters in the cookie string to their

// english notation var myCookie = unescape( document.cookie ); // split the cookie into tokens using = as delimiter var cookieTokens = myCookie.split( "=" ); // set name to the part of the cookie that follows the = sign name = cookieTokens[ 1 ]; } else { // if there was no cookie then ask the user to input a name name = window.prompt( "Please enter your name", "GalAnt" );

// escape non-alphanumeric characters in the name string // and add name to the cookie

document.cookie = "name=" + escape( name ); }

Page 134: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document object

document.writeln( name + ", welcome to JavaScript programming! </h1>" ); document.writeln( "<a href= \" JavaScript:wrongPerson() \" > " + "Click here if you are not " + name + "</a>" ); // reset the document's cookie if wrong person function wrongPerson() { // reset the cookie document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT"; // after removing the cookie reload the page to get a new name location.reload(); }</script> </head> <body><p>Click Refresh (or Reload) to run the script again</p> </body></html>

Page 135: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document object

Page 136: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Document object

Page 137: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Event model-onclick

<html > <head> <title>DHTML Event Model - onclick</title>

<script type = "text/javascript" for = "para" event = "onclick">

alert( "Hi there" );</script>

</head> <body> <p id = "para">Click on this text!</p> <input type = "button" value = "Click Me!" onclick = "alert( 'Hi again' )" />

</body>

</html>

Page 138: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 139: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 140: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Comments

• Comments are as in C or Java:• Between // and the end of the line• Between /* and */

• Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments; they have no special meaning in JavaScript

Page 141: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Objects

• Objects have attributes and methods.• Many pre-defined objects and object

types.• Using objects follows the syntax of Java:

objectname.attributenameobjectname.methodname()

Page 142: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The Math Object

• Access to mathematical functions and constants.

• Constants: Math.PI

• Methods: Math.random()Math.abs(x), Math.ceil(x)Math.sin(x), Math.floor(x)Math.cos(x), Math.exp(x)Math.max(x,y), Math.log(x)Math.min(x,y), Math.round(x),Math.sqrt(x), Math.pow(x,y)

Page 143: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Math object in use

// returns an integer between 1 and 6function roll() { var x = Math.random();

// convert to range [0,6.0) x = x * 6; // add 1 and convert to int return parseInt(1+x );}

document.writeln("Roll is “ + roll() );

Page 144: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Predefined Objects

• JavaScript also includes some objects that are automatically created for you (always available).• document• navigator• window

Page 145: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The document object Methods:• document.write() like a print statement – the

output goes into the HTML document.

document.write("My title is" + document.title+ “URL is” +document.URL);

string concatenation!

Page 146: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript Example

<HEAD><TITLE>JavaScript is Javalicious</TITLE></HEAD><BODY><H3>I am a web page and here is my

name:</H3><SCRIPT>document.write(document.title);</SCRIPT><HR>

<HEAD><TITLE>JavaScript is Javalicious</TITLE></HEAD><BODY><H3>I am a web page and here is my

name:</H3><SCRIPT>document.write(document.title);</SCRIPT><HR>

Page 147: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

JavaScript and HTML Comments

<SCRIPT><!--document.write("Hi Dave");document.bgColor="BLUE";--></SCRIPT> HTM

L co

mm

ent

Page 148: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The navigator Object

• Represents the browser. Read-only!• Attributes include:

appNameappVersionplatform

often used to

determine what k

ind of

browser is being used

(Netscape vs. IE)

Page 149: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

navigator Example

• alert(navigator.appName);• alert(navigator.appVersion);• alert(navigator.platform);

Page 150: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The window Object

• Represents the current window.

• There are possible many objects of type Window, the predefined object window represents the current window.

• Access to, and control of, a number of properties including position and size.

Page 151: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

window attributes

• document • name• status the status line• parent

Page 152: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

some window methods

alert()close()prompt()moveTo() moveBy()open()scroll() scrollTo()resizeBy() resizeTo()

Page 153: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

The with statement

• with (object) statement ; uses the object as the default prefix for variables in the statement

• For example, the following are equivalent:• with (document.myForm) {

result.value = compute(myInput.value) ;}

• document.myForm.result.value = compute(document.myForm.myInput.value);

• One of my books hints at mysterious problems resulting from the use of with, and recommends against ever using it

Page 154: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

for .. in statement

• You can loop through all the properties of an object with for (variable in object) statement;

• <script language="javascript">• var a = new Array(4);

• for (i=0;i<a.length;i++)• {• a[i]=i;• }• for (j in a) • {• document.writeln(j);• }• </script>

Page 155: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 156: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 157: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 158: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 159: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

• DHTML stands for Dynamic HTML.• DHTML is the art of making HTML pages

dynamic!• DHTML is a combination of technologies

used to create dynamic and interactive Web sites.

• To most people DHTML means a combination of HTML, Style Sheets and JavaScript.

Page 160: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Event Occurs when...

onabort a user aborts page loading

onblur a user leaves an object

onchangea user changes the value of an object

onclick a user clicks on an object

ondblclick a user double-clicks on an object

onfocus a user makes an object active

onkeydown a keyboard key is on its way down

onkeypress a keyboard key is pressed

onkeyup a keyboard key is released

Page 161: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Event Occurs when...

onload a page is finished loading.

onmousedown a user presses a mouse-button

onmousemove a cursor moves on an object

onmouseover a cursor moves over an object

onmouseout a cursor moves off an object

onmouseup a user releases a mouse-button

onreset a user resets a form

onselect a user selects content on a page

onsubmit a user submits a form

onunload a user closes a page

Page 162: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Mousedown

<body onmousedown="document.bgColor='yellow'">

<center> <h1> Welcome to DHTML Programs </h1> </center>

</body>

Page 163: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Mouseover

<body><center> <h1> Using Dynamic

Styles</h1> <span

onmouseover="this.style.fontSize='48'"> This text gets bigger when U move the mouse over it!

</span></center></body>

Page 164: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

DHTML using Javascript<body><center> <h1> Creating a Self modifying

webpage</h1> <script language="javascript">if(confirm("Do u want large image ?")){document.write("<br><img width=1024

height=1024 src=‘Tulips.jpg'>") }else{document.write("<br><img width=120 height=120

src='1.bmp'>")}</script></center></body>

Page 165: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Change the Cursor

<body><center> <h1 onmouseover="this.style.cursor='hand'"

onmouseout="this.style.cursor='defalut'"> Change the cursor with the mouse</h1> </center></body>

Page 166: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Mouseover & MouseOut

<body>

<center> <h1 onmouseover="this.style.color='red'" onmouseout="this.style.color='blue'"> Turn me red with the mouse</h1>

</center>

</body>

Page 167: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Mouseover & MouseOut (pictures)

• <body>• <center> <h1> Mouse Over Image Handling

</h1>• <img src="2.jpg" onmouseover="this.src='

Lighthouse.jpg'" onmouseout="this.src=' Tulips.jpg'">

• </center>• </body>

Page 168: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Mouseover & MouseOut

<body>

<center> <h1 onmouseover="this.style.color='red'"

onmouseout="this.style.color='blue'"> Turn me red with the mouse</h1>

</center>

</body>

Page 169: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,
Page 170: Java script. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

Thank you