90
Java Script • JavaScript is THE scripting language of the Web. • JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. • JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

Java Script Class 1

Embed Size (px)

Citation preview

Page 1: Java Script Class 1

Java Script

• JavaScript is THE scripting language of the Web.• JavaScript is used in billions of Web pages to add

functionality, validate forms, communicate with the server, and much more.

• JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

Page 2: Java Script Class 1

What is JavaScript?• JavaScript was designed to add interactivity to HTML

pages• JavaScript is a scripting language• A scripting language is a lightweight programming

language• JavaScript is usually embedded directly into HTML

pages• JavaScript is an interpreted language (means that

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

license

Page 3: Java Script Class 1

Are Java and JavaScript the same?

• NO!• Java and JavaScript are two completely

different languages in both concept and design!

• Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

Page 4: Java Script Class 1

Java Java Script

The code is compiled and downloaded from the server, but executed at the client.

Client interprets it but does not compile.

Java is a Object Oriented language. Objects are divided into classes and instances with all inheritance through the class hierarchy. Properties and methods cannot be added to classes and instances dynamically.

It is Object based language. Inheritance is through the prototype mechanism and properties and methods can be added to any object dynamically.

Java applets are distinct from HTML, but are accessed from HTML.

The Java Script code is integrated with and embedded in HTML.

Variable data types must be declared Variable data types need not to be declared.

It is Early binding. Object reference must exist at compile time.

It is Late binding. Object references checked at run time.

Page 5: Java Script Class 1

What Can JavaScript do?• JavaScript gives HTML designers a programming tool - HTML authors are

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

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

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

• JavaScript can be used to validate data - A JavaScript can be used to validate form input

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

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

Page 6: Java Script Class 1

JavaScript = ECMAScript (European Computer Manufacturers Association) • JavaScript is an implementation of the ECMAScript

language standard. ECMA-262 is the official JavaScript standard.

• JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996.

• The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997.

• The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998.

• The development is still in progress.

Page 7: Java Script Class 1

JavaScript How To

• The HTML <script> tag is used to insert a JavaScript into an HTML document.

• The HTML "id" attribute is used to identify HTML elements.

Page 8: Java Script Class 1

Manipulating HTML Elements

• JavaScript is typically used to manipulate existing HTML elements.

• The HTML "id" attribute is used to identify HTML elements.

• To access an HTML element from a JavaScript, use the document.getElementById() method.

• The document.getElementById() method will access the HTML element with the specified id.

Page 9: Java Script Class 1

Example : Access the HTML element with the specified id, and change its content

<!DOCTYPE html><html><body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script type="text/javascript">document.getElementById("demo").innerHTML="My First JavaScript";</script>

</body></html>

Page 10: Java Script Class 1

Write Directly into The HTML Document

<!DOCTYPE html><html><body>

<h1>My First Web Page</h1>

<script type="text/javascript">document.write("<p>My First JavaScript</p>");</script>

</body></html>

Page 11: Java Script Class 1

JavaScript Where To

• JavaScripts can be put in the <body> and in the <head> sections of an HTML page.

Page 12: Java Script Class 1

JavaScript in <body>• The example below manipulate the content of an existing <p>

element when the page loads:• <!DOCTYPE html>

<html><body> <h1>My Web Page</h1>

<p id="demo">A Paragraph</p> <script type="text/javascript">

document.getElementById("demo").innerHTML="My First JavaScript";</script>

</body></html> Note: The JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.

Page 13: Java Script Class 1

JavaScript Functions and Events

• The JavaScript statement in the example above, is executed when the page loads, but that is not always what we want.

• Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Then we put the script inside a function.

• Functions are normally used in combination with events.

Page 14: Java Script Class 1

JavaScript Functions in <head>• The example below calls a function when a button is clicked:

<!DOCTYPE html><html> <head><script type="text/javascript">function myFunction(){document.getElementById("demo").innerHTML="My First JavaScript Function";}</script></head>

<body><h1>My Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button></body>

</html>

Page 15: Java Script Class 1

JavaScript Functions in <body>• This example also calls a function when a button is clicked, but the script

is placed at the bottom of the page:<!DOCTYPE html>

<html><body> <h1>My Web Page</h1>

<p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button><script type="text/javascript">

function myFunction(){document.getElementById("demo").innerHTML="My First JavaScript Function";}</script>

</body></html>

Page 16: Java Script Class 1

Scripts in <head> and <body>

• You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.

• It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Page 17: Java Script Class 1

Using an External JavaScript

• JavaScript can also be placed in external files. • External JavaScript files often contain code to

be used on several different web pages. • External JavaScript files have the file extension

.js.• Note: External script cannot contain the

<script></script> tags!• To use an external script, point to the .js file in

the "src" attribute of the <script> tag:

Page 18: Java Script Class 1

Example

• <!DOCTYPE html><html><body><script type="text/javascript" src="myScript.js"></script></body></html>

• Note: You can place the script in the head or body as you like.

• Note: The script will behave as it was located in the document, exactly where you put it.

Page 19: Java Script Class 1

JavaScript Statements• JavaScript is a sequence of statements to be

executed by the browser.• JavaScript is Case Sensitive.• A JavaScript statement is a command to a

browser. The purpose of the command is to tell the browser what to do.

• This JavaScript statement tells the browser to write "Hello Dolly" to an HTML element:

document.getElementById("demo").innerHTML="Hello Dolly";

Page 20: Java Script Class 1

• It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.

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

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

Page 21: Java Script Class 1

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 manipulate two HTML

elements:

document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?“;

Page 22: Java Script Class 1

JavaScript Blocks

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

• The purpose of a block is to make the sequence of statements execute together.

• An example of statements grouped together in blocks, are JavaScript functions.

• This example will run a function that will manipulate two HTML elements:

Page 23: Java Script Class 1

function myFunction(){document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?";}

Page 24: Java Script Class 1

JavaScript Comments

• JavaScript comments can be used to make the code more readable.

• Single line comments start with //.• Multi line comments start with /* and end

with */.

Page 25: Java Script Class 1

JavaScript Variables

• Variables are "containers" for storing information.

• 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, the $

character, or the underscore character

Page 26: Java Script Class 1

Declaring (Creating) JavaScript Variables

• You declare JavaScript variables with the var keyword: Ex: var carname;

• After the declaration shown above, the variable is empty (it has no value yet). To assign a value to the variable, use the equal (=) sign: carname="Volvo";

• However, you can also assign a value to the variable when you declare it:

var carname="Volvo";• To write the value inside an HTML element,

simply refer to it by using it's variable name:

Page 27: Java Script Class 1

<!DOCTYPE html><html><body><p>Click the button to create a variable, and display the result.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script type="text/javascript">function myFunction(){var carname="Volvo";document.getElementById("demo").innerHTML=carname;}</script></body></html>

Page 28: Java Script Class 1

• Note: When you assign a text value to a variable, put quotes around the value.

• Note: When you assign a numeric value to a variable, do not put quotes around the value, if you put quotes around a numeric value, it will be treated as text.

• Note: If you redeclare a JavaScript variable, it will not lose its value.

Page 29: Java Script Class 1

Local JavaScript Variables

• A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope).

• You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

• Local variables are deleted as soon as the function is completed.

Page 30: Java Script Class 1

Global JavaScript Variables• Variables declared outside a function, become

GLOBAL, and all scripts and functions on the web page can access it.

• Global variables are deleted when you close the page.

• If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. This statement:

carname="Volvo"; will declare the variable carname as a global

variable (if it does not already exist).

Page 31: Java Script Class 1

JavaScript Arithmetic

• you can do arithmetic operations with JavaScript variables:

<!DOCTYPE html><html><body><p>Given that y=5, calculate x=y+2, and display the result.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script type="text/javascript">function myFunction(){var y=5;var x=y+2;

Page 32: Java Script Class 1

var demoP=document.getElementById("demo")demoP.innerHTML="x=" + x;}</script></body></html>

Page 33: Java Script Class 1

JavaScript Operators

• = is used to assign values.• +, -, *, / (gives float values), %, ++, --, +=, -=,*=,

/+,%=.• + operator can also be used on strings to

concatenation.• txt1="What a very";

txt2="nice day";txt3=txt1+txt2; (or) txt3=txt1+" "+txt2;

Page 34: Java Script Class 1

• Adding two numbers, will return the sum, but adding a number and a string will return a string:

• x=5+5;y="5"+5;z="Hello"+5;Resulted as 10

55Hello5

Page 35: Java Script Class 1

• Comparison and Logical operators are used to test for true or false.

• if (age<18) x="Too young";

Page 36: Java Script Class 1

Conditional Operator:

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.Syntax:variablename=(condition)?value1:value2Ex:voteable=(age<18)?"Too young":"Old enough“;

Page 37: Java Script Class 1

JavaScript If...Else Statements• Conditional statements are used to perform different

actions based on different conditions.• In JavaScript we have the following conditional statements:• if statement - use this statement to execute some code

only if a specified condition is true• if...else statement - use this statement to execute some

code if the condition is true and another code if the condition is false

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

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

Page 38: Java Script Class 1

If Statement• if (condition)

{  code to be executed if condition is true }

• if (condition) {  code to be executed if condition is true }else {  code to be executed if condition is not true }

Page 39: Java Script Class 1

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

Page 40: Java Script Class 1

<!DOCTYPE html><html><body><p>Click the button to get a time-based greeting.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script type="text/javascript">function myFunction(){var x="";var time=new Date().getHours();if (time<10) { x="Good morning"; }

Page 41: Java Script Class 1

else if (time<20) { x="Good day"; }else { x="Good evening"; }document.getElementById("demo").innerHTML=x;}</script></body></html>

Page 42: Java Script Class 1

<!DOCTYPE html><html><body><p id="demo"></p><script type="text/javascript">var r=Math.random();var x=document.getElementById("demo")if (r>0.5){x.innerHTML="<a href='http://w3schools.com'>Visit W3Schools</a>";}else{x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>";}</script></body></html>

Page 43: Java Script Class 1

JavaScript Switch Statement

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

• Use the switch statement to select one of many blocks of code to be executed.

• The switch statement can be replaced by performing many if-then-else-if conditions, but when the answer of an evaluation can give you many different answers, the switch-case statement can be more efficient.

Page 44: Java Script Class 1

switch(n){case 1:  execute code block 1 break;case 2:  execute code block 2 break;default:  code to be executed if n is different from case 1 and 2}

Page 45: Java Script Class 1

how it works:

• First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed.

• Use break to prevent the code from running into the next case automatically.

• Use the default keyword to specify what to do if there is no match

Page 46: Java Script Class 1

Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:

<!DOCTYPE html><html><body>

<p>Click the button to display what day it is today.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script type="text/javascript">function myFunction(){var x;var d=new Date().getDay();switch (d)

Page 47: Java Script Class 1

{ case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break;

case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break;default:

  x="Looking forward to the Weekend";

}document.getElementById("demo")

.innerHTML=x;}</script></body></html>

Page 48: Java Script Class 1

JavaScript Popup Boxes

• JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt 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("sometext");

Page 49: Java Script Class 1

• <!DOCTYPE html><html><head><script type="text/javascript">function myFunction(){alert("I am an alert box!");}</script></head><body>

<input type="button" onclick="myFunction()" value="Show alert box" />

</body></html>

Page 50: Java Script Class 1

Confirm Box

• A confirm box is often used if you want the user to verify or accept something.

• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

• Syntax: confirm("sometext");

Page 51: Java Script Class 1

var r=confirm("Press a button");if (r==true) { x="You pressed OK!"; }else { x="You pressed Cancel!"; }

Page 52: Java Script Class 1

Prompt Box

• A prompt box is often used if you want the user to input a value before entering a page.

• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

• Syntax: prompt("sometext","defaultvalue");

Page 53: Java Script Class 1

var name=prompt("Please enter your name","Harry Potter");if (name!=null && name!="") { x="Hello " + name + "! How are you today?"; }

Line Breaks :To display line breaks inside a popup box, use a

back-slash followed by the character n.Syntax: alert("Hello\nHow are you?");

Page 54: Java Script Class 1

JavaScript Functions• A function can be executed by an event, like

clicking a button.• A function is a block of code that executes only

when you tell it to execute.• It can be when an event occurs, like when a user

clicks a button, or from a call within your script, or from a call within another function.

• Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.

Page 55: Java Script Class 1

• Syntax: function functionname()

{some code}

Calling a Function with Arguments :• When you call a function, you can pass along

some values to it, these values are called arguments or parameters. These arguments can be used inside the function.

Page 56: Java Script Class 1

• You can send as many arguments as you like, separated by commas (,).

Ex: myFunction(argument1,argument2)• Declare the argument, as variables, when you

declare the function:function myFunction(var1,var2)

{some code}

Page 57: Java Script Class 1

• Ex: <button onclick="myFunction('Harry

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

Page 58: Java Script Class 1

Functions With a Return Value• Sometimes you want your function to return a value

back to where the call was made. This is possible by using the return statement.

• When using the return statement, the function will stop executing, and return the specified value.

• Ex: function myFunction()

{var x=5;return x;}

The function above will return the value 5.

Page 59: Java Script Class 1

• The function-call will be replaced with the return value:

var myVar=myFunction(); The variable myVar holds the value 5, which is

what the function "myFunction()" returns.• You can also use the returnvalue without

storing it as a variable: document.getElementById("demo").innerHTML=myFunction();

Page 60: Java Script Class 1

• function myFunction(a,b){return a*b;}document.getElementById("demo").innerHTML=myFunction(4,3);

• The innerHTML of the "demo" element will be: 12

Page 61: Java Script Class 1

• The return statement is also used when you simply want to exit a function. The return value is optional:

function myFunction(a,b){if (a>b) { return; }x=a+b}

The function above will exit the function if a>b, and will not calculate the sum of a and b.

Page 62: Java Script Class 1

The Lifetime of JavaScript Variables

• If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.

• If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Page 63: Java Script Class 1

JavaScript For Loop

• For Loops will execute a block of code a specified number of times.

• The for loop is used when you know in advance how many times the script should run.

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

Page 64: Java Script Class 1

Example:<!DOCTYPE html><html><body><p>Click the button to loop through a block of code five times.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script type="text/javascript">function myFunction(){var x="",i;for (i=0;i<5;i++) { x=x + "The number is " + i + "<br />"; }document.getElementById("demo").innerHTML=x;}</script></body></html>

Page 65: Java Script Class 1

JavaScript While Loop• While Loops execute a block of code as long as a

specified condition is true.• Syntax: while (variable<endvalue)

{  code to be executed }

• Ex: while (i<5)

{ x=x + "The number is " + i + "<br />"; i++; }

Page 66: Java Script Class 1

The do...while Loop• The do...while loop is a variant of the while loop.

This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

• Syntax: do

{  code to be executed  }while (variable<endvalue);

Page 67: Java Script Class 1

• do { x=x + "The number is " + i + "<br />"; i++; }while (i<5);

The break Statement :• The break statement will break the loop and

continue executing the code that follows after the loop (if any).

Page 68: Java Script Class 1

• for (i=0;i<10;i++) {

if (i==3) { break; } x=x + "The number is " + i + "<br />"; }

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

with the next value.• for (i=0;i<=10;i++)

{ if (i==3) { continue; } x=x + "The number is " + i + "<br />"; }

Page 69: Java Script Class 1

JavaScript For...In Statement• The for...in statement loops through the properties of an object.• Syntax: for (variable in object)

{  code to be executed }

• The block of code inside of the for...in loop will be executed once for each property.

• Looping through the properties of an object: var person={fname:"John",lname:"Doe",age:25};

for (x in person) { txt=txt + person[x]; }

Page 70: Java Script Class 1

JavaScript Events• Events are actions that can be detected by JavaScript.<!DOCTYPE html>

<html><head><script type="text/javascript">function displayDate(){document.getElementById("demo").innerHTML=Date();}</script></head><body><h1>My First Web Page</h1><p id="demo"></p><button type="button" onclick="displayDate()">Display Date</button></body></html>

Page 71: Java Script Class 1

Events• By using JavaScript, we have the ability to create dynamic web

pages. Events are actions that can be detected by JavaScript.• Every element on a web page has certain events which can trigger

a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

• Examples of events:A mouse clickA web page or an image loadingMousing over a hot spot on the web pageSelecting an input field in an HTML formSubmitting an HTML formA keystroke

Page 72: Java Script Class 1

• Events are normally used in combination with functions, and the function will not be executed before the event occurs!

• onLoad and onUnload:– The onLoad and onUnload events are triggered when

the user enters or leaves the page.– The onLoad event is often used to check the visitor's

browser type and browser version, and load the proper version of the web page based on the information.

Page 73: Java Script Class 1

– Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

Page 74: Java Script Class 1

• onFocus, onBlur and onChange: – The onFocus, onBlur and onChange events are

often used in combination with validation of form fields.

– Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:

– <input type="text" size="30" id="email" onchange="checkEmail()" />

Page 75: Java Script Class 1

• onSubmit:– The onSubmit event is used to validate ALL form fields

before submitting it.– Below is an example of how to use the onSubmit

event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:

– <form method="post" action="xxx.htm" onsubmit="return checkForm()">

Page 76: Java Script Class 1

• onMouseOver:– The onmouseover event can be used to trigger a

function when the user mouses over an HTML element.

Page 77: Java Script Class 1

<!DOCTYPE html><html><head><script type="text/javascript">function writeText(txt){document.getElementById("desc").innerHTML=txt;}</script></head><body><img src ="planets.gif" width ="145" height ="126" alt="Planets"

usemap="#planetmap" /><map name="planetmap"><area shape ="rect" coords ="0,0,82,126"onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by

far the largest objects in our Solar System.')"href ="sun.htm" target ="_blank" alt="Sun" />

Page 78: Java Script Class 1

<area shape ="circle" coords ="90,58,3"onmouseover="writeText('The planet Mercury is very difficult to

study from the Earth because it is always so close to the Sun.')"href ="mercur.htm" target ="_blank" alt="Mercury" /><area shape ="circle" coords ="124,58,8"onmouseover="writeText('Until the 1960s, Venus was often

considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"

href ="venus.htm" target ="_blank" alt="Venus" /></map> <p id="desc">Mouse over the sun and the planets and see the

different descriptions.</p></body></html>

Page 79: Java Script Class 1

JavaScript Try...Catch Statement

• The try...catch statement allows you to test a block of code for errors.

• When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

• how to catch and handle JavaScript error messages, so you don't lose your audience.

Page 80: Java Script Class 1

• The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

• try { //Run some code here }catch(err) { //Handle errors here }

Page 81: Java Script Class 1

<!DOCTYPE html><html><head><script type="text/javascript">var txt="";function message(){try { adddlert("Welcome guest!"); //Here we written alert function spelled wrongly. }catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); }}</script></head><body><input type="button" value="View message" onclick="message()" /></body></html>

Page 82: Java Script Class 1

• The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:

Page 83: Java Script Class 1

<!DOCTYPE html><html><head><script type="text/javascript">var txt="";function message(){try { adddlert("Welcome guest!"); }catch(err) { txt="There was an error on this page.\n\n";

Page 84: Java Script Class 1

txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } }}</script></head>

<body><input type="button" value="View message" onclick="message()" /></body>

</html>

Page 85: Java Script Class 1

The throw Statement

• The throw statement can be used together with the try...catch statement, to create an exception for the error and you can control program flow and generate accurate error messages.

• Syntax: throw exception • The exception can be a string, integer,

Boolean or an object.

Page 86: Java Script Class 1

<!DOCTYPE html><html><body><script type="text/javascript">var x=prompt("Enter a number between 5 and 10:","");try { if(x>10) { throw "Err1"; } else if(x<5) { throw "Err2"; } else if(isNaN(x)) { throw "Err3"; } }

Page 87: Java Script Class 1

catch(err) { if(err=="Err1") { document.write("Error! The value is too high."); } if(err=="Err2") { document.write("Error! The value is too low."); } if(err=="Err3") { document.write("Error! The value is not a number."); } }</script></body></html>

Page 88: Java Script Class 1

JavaScript Special Characters

• In JavaScript you can add special characters to a text string by using the backslash sign.

• The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

• var txt="We are the so-called \"Vikings\" from the north.";document.write(txt);

Page 89: Java Script Class 1

• Code Outputs \' single quote \" double quote \\ backslash \n new line \r carriage return \t tab \b backspace \f form feed

Page 90: Java Script Class 1

Break up a Code Line

• You can break up a code line within a text string with a backslash. The example below will be displayed properly:

document.write("Hello \World!");

• However, you cannot break up a code line like this:

document.write \("Hello World!");