JavaScript 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
You Should Already Know
Before you continue you should have
a basic understanding of the following:
- HTML and CSS
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
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++.
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
JavaScript
= ECMAScript
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.
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.
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.
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>
<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>
Example
Explained
To insert a JavaScript into an HTML
page, use the <script> tag.
Inside the <script> tag use
the type attribute to define the scripting language.
The <script> and
</script> tells where the JavaScript starts and ends.
The lines between the <script>
and </script> contain the JavaScript and are executed by the browser:
<p id="demo">My
First Paragraph.</p>
<script type="text/javascript">
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
<script type="text/javascript">
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
In this case, the browser will
access the HTML element with id="demo", and replace the content with
"My First JavaScript".
Some
Browsers do Not Support JavaScript
Browsers that do not support
JavaScript, will display JavaScript as page content.
To prevent them from doing this, and
as a part of the JavaScript standard, the HTML comment tag should be used to
"hide" the JavaScript.
Just add an HTML comment tag <!--
before the first JavaScript statement, and a --> (end of comment) after the
last JavaScript statement, like this:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML="My First JavaScript";
//-->
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML="My First JavaScript";
//-->
</script>
</body>
</html>
The two forward slashes at the end
of comment line (//) is the JavaScript comment symbol. This prevents JavaScript
from executing the --> tag.
Write
Directly into The HTML Document
The example below writes a <p>
element into the HTML document:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>My First JavaScript</p>");
</script>
</body>
</html>
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>My First JavaScript</p>");
</script>
</body>
</html>
JavaScript Where To
JavaScripts can be put in the
<body> and in the <head> sections of an HTML page.
JavaScript
in <body>
The example below manipulate the
content of an existing <p> element when the page loads:
Example
<!DOCTYPE html>
<html>
<body>
<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>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
</body>
</html>
</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.
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.
You will learn more about JavaScript
functions and events in later chapters.
JavaScript
Functions in <head>
The example below calls a function
when a button is clicked:
Example
<!DOCTYPE html>
<html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</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>
</html>
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:
Example
<!DOCTYPE html>
<html>
<body>
<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>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</body>
</html>
</html>
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.
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:
Example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="myScript.js"></script>
</body>
</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.
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.
JavaScript
Statements
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";
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. 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.
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:
Example
document.getElementById("demo").innerHTML="Hello
Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
document.getElementById("myDIV").innerHTML="How are you?";
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:
Example
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
Variables are "containers"
for storing information.
Do
You Remember Algebra From School?
Do you remember algebra from school?
x=5, y=6, z=x+y
Do you remember that a letter (like
x) could be used to hold a value (like 5), and that you could use the
information above to calculate the value of z to be 11?
These letters are called variables,
and variables can be used to hold values (x=5) or expressions (z=x+y).
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, the $ character, or the underscore character
Note: Because JavaScript is case-sensitive, variable names are
case-sensitive.
Declaring
(Creating) JavaScript Variables
Creating a variable in JavaScript is
most often referred to as "declaring" a variable.
You declare JavaScript variables
with the var keyword:
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";
After the execution of the statement
above, the carname will hold the value Volvo.
To write the value inside an HTML
element, simply refer to it by using it's variable name:
Example
var
carname="Volvo";
document.getElementById("myP").innerHTML=carname;
document.getElementById("myP").innerHTML=carname;
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.
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.
You will learn more about functions
in a later chapter of this tutorial.
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.
Assigning
Values to Undeclared JavaScript Variables
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).
JavaScript
Arithmetic
As with algebra, you can do
arithmetic operations with JavaScript variables:
Example
y=5;
x=y+2;
x=y+2;
You will learn more about the
operators that can be used in the next chapter of this tutorial.
avaScript Operators
= is used to assign values.
+ is used to add values.
The assignment operator = is
used to assign values to JavaScript variables.
The arithmetic operator + is used to
add values together.
Example
Assign values to variables
and add them together:
y=5;
z=2;
x=y+z;
z=2;
x=y+z;
The result of x will be:
7
JavaScript
Arithmetic Operators
Arithmetic operators are used to
perform arithmetic between variables and/or values.
Given that y=5, the table
below explains the arithmetic operators:
Operator
|
Description
|
Example
|
Result of x
|
Result of y
|
Try it
|
+
|
Addition
|
x=y+2
|
7
|
5
|
|
-
|
Subtraction
|
x=y-2
|
3
|
5
|
|
*
|
Multiplication
|
x=y*2
|
10
|
5
|
|
/
|
Division
|
x=y/2
|
2.5
|
5
|
|
%
|
Modulus (division remainder)
|
x=y%2
|
1
|
5
|
|
++
|
Increment
|
x=++y
|
6
|
6
|
|
x=y++
|
5
|
6
|
|||
--
|
Decrement
|
x=--y
|
4
|
4
|
|
x=y--
|
5
|
4
|
JavaScript
Assignment Operators
Assignment operators are used to
assign values to JavaScript variables.
Given that x=10 and y=5,
the table below explains the assignment operators:
Operator
|
Example
|
Same As
|
Result
|
Try it
|
=
|
x=y
|
|
x=5
|
|
+=
|
x+=y
|
x=x+y
|
x=15
|
|
-=
|
x-=y
|
x=x-y
|
x=5
|
|
*=
|
x*=y
|
x=x*y
|
x=50
|
|
/=
|
x/=y
|
x=x/y
|
x=2
|
|
%=
|
x%=y
|
x=x%y
|
x=0
|
The
+ Operator Used on Strings
The + operator can also be used to
add string variables or text values together.
Example
To add two or more string
variables together, use the + operator.
txt1="What a
very";
txt2="nice day";
txt3=txt1+txt2;
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a verynice day
To add a space between the two
strings, insert a space into one of the strings:
Example
txt1="What a very
";
txt2="nice day";
txt3=txt1+txt2;
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a very nice day
or insert a space into the
expression:
Example
txt1="What a
very";
txt2="nice day";
txt3=txt1+" "+txt2;
txt2="nice day";
txt3=txt1+" "+txt2;
The result of txt3
will be:
What a very nice day
Adding
Strings and Numbers
Adding two numbers, will return the
sum, but adding a number and a string will return a string:
Example
x=5+5;
y="5"+5;
z="Hello"+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and
z will be:
10
55
Hello5
55
Hello5
The rule is: If you add a number
and a string, the result will be a string!
avaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm
box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the user.When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");
Example
<!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>
<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>
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");
Example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
var name=prompt("Please enter your
name","Harry Potter");
if (name!=null && name!="")
{
x="Hello " + name + "! How are you today?";
}
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.Example
alert("Hello\nHow are you?");
JavaScript Functions
A function can be executed by an event, like clicking a button.
JavaScript Functions
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.
How to Define a Function
Syntax
function functionname()
{
some code
}
The { and the } defines the start and end of the function.{
some code
}
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
JavaScript Function Example
Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
The function is executed when the user clicks the button.<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
You will learn more about JavaScript events in the JS Events chapter.
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.Theese arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first
variable is given the value of the first passed argument etc.{
some code
}
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<script type="text/javascript">
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard"
when the button is clicked.<script type="text/javascript">
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function is flexible, you can call the function using different arguments, and different welcome messages will be given:
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
The example above will alert "Welcome Harry Potter, the Wizard" or
"Welcome Bob, the Builder" depending on which button is clicked.<button onclick="myFunction('Bob','Builder')">Try it</button>
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.
Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.{
var x=5;
return x;
}
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:
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();
The innerHTML of the "demo" element will be 5, which is what the
function "myFunction()" returns.You can make a returnvalue based on arguments passed into the function:
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
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.{
if (a>b)
{
return;
}
x=a+b
}
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.
JavaScript Events
Events are actions that can be
detected by JavaScript.
Acting
to an Event
The example below displays the date
when a button is clicked:
Example
<!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>
<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>
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 click
- A web page or an image loading
- Mousing over a hot spot on the web page
- Selecting an input field in an HTML form
- Submitting an HTML form
- A keystroke
Note: 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.
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!".
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()" />
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()">
onMouseOver
The onmouseover event can be used to
trigger a function when the user mouses over an HTML element:
Example


Mouse over the sun and the planets
and see the different descriptions.
JavaScript Try...Catch Statement
The try...catch statement allows you to test a block of code for
errors.
JavaScript - Catching 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.This chapter will teach you how to catch and handle JavaScript error messages, so you don't lose your audience.
The try...catch Statement
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.Syntax
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
Note that try...catch is written in lowercase letters. Using uppercase
letters will generate a JavaScript error!{
//Run some code here
}
catch(err)
{
//Handle errors here
}
Examples
The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened:Example
<!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";
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>
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:<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";
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>
Example
<!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";
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>
<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";
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>
The throw Statement
The throw statement can be used together with the try...catch statement, to create an exception for the error. Learn about the throw statement in the next chapter.JavaScript Throw Statement
The throw statement allows you to create an exception.
The Throw Statement
The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.Syntax
throw exception
The exception can be a string, integer, Boolean or an object.Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!
Example
The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 5, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:Example
<!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";
}
}
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>
<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";
}
}
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>
JavaScript Special Characters
In JavaScript you can add special
characters to a text string by using the backslash sign.
Insert
Special Characters
The backslash (\) is used to insert
apostrophes, new lines, quotes, and other special characters into a text
string.
Look at the following JavaScript
code:
var txt="We are the so-called
"Vikings" from the north.";
document.write(txt);
document.write(txt);
In JavaScript, a string is started
and stopped with either single or double quotes. This means that the string
above will be chopped to: We are the so-called
To solve this problem, you must
place a backslash (\) before each double quote in "Viking". This
turns each double quote into a string literal:
var txt="We are the so-called
\"Vikings\" from the north.";
document.write(txt);
document.write(txt);
JavaScript will now output the
proper text string: We are the so-called "Vikings" from the north.
The table below lists other special
characters that can be added to a text string with the backslash sign:
Code
|
Outputs
|
\'
|
single quote
|
\"
|
double quote
|
\\
|
backslash
|
\n
|
new line
|
\r
|
carriage return
|
\t
|
tab
|
\b
|
backspace
|
\f
|
form feed
|
JavaScript Guidelines
Some other important things to know
when scripting with JavaScript.
JavaScript
is Case Sensitive
A function named
"myfunction" is not the same as "myFunction" and a variable
named "myVar" is not the same as "myvar".
JavaScript is case sensitive -
therefore watch your capitalization closely when you create or call variables,
objects and functions.
White
Space
JavaScript ignores extra spaces. You
can add white space to your script to make it more readable. The following
lines are equivalent:
var name="Hege";
var name = "Hege";
var name = "Hege";
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!");
World!");
However, you cannot break
up a code line like this:
document.write \
("Hello World!");
("Hello World!");
No comments:
Post a Comment