Introduction

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.


What can a JavaScript Do?


 document.write("...") JScript Command

JavaScript commands are written within the <script> and </script> tags. The type attribute is used to define the scripting language:
<script type="text/javascript">Script here within tags</script>




The above bold text was retrieved from an external file
It uses the code: <script src="ExtScript.js"></script>


Variables


Lifetime of a Variable

When you declare a variable 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.

The "if.. / ..else" Statement


The "if.. / ..else if.. / ..else" Statement


Switch Statement


Operators


Popup Boxes

 <input type="button" value="Display alert box" onclick="disp_alert()" />

 <input type="button" value="Display Confirm Box" onclick="disp_Confirm()" />

 <input type="button" value="Display Prompt Box" onclick="disp_prompt()" />

Functions

A function is a reusable code-block that will be executed by an event, or when the function is called.

Loops

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. In JavaScript there are only two different kind of loops:


The "for" Loop

Syntax: for (var=startvalue;var<=endvalue;var=var+increment) {code to be executed}
Example:
for(i=1;i<=6;i++){
document.write("<h"+i+" style='background-color:transparent'>This is for loop "+i+"</h"+i+">")
}

Result of Example Code:

The "while" Loop

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. The basic syntax is given below:
while (var<=endvalue){code to be executed}

Example: This prints 11 lines of code from i=0 to 10
var i=0
while (i<=10){
  document.write("The number is " + i)
  document.write("<br />")
  i=i+1
}

The "do...while" Loop

This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested. The basic syntax is given below:

do{
  code to be executed
}while (var<=endvalue)
Example: This code yields only one line of code "The number is 0" even if the condition is false
var i=0
do{
  document.write("The number is " + i)
  document.write("<br />")
  i=i+1
}while (i<0)

Break and Continue

There are two special statements that can be used inside loops: break and continue.


break

The break command will break the loop and continue executing the code that follows after the loop (if any).

Example: This code only yields 3 lines of code from "The number is 0" to 2 because of the break statement
var i=0
for(i=1;i<=10;i++){
  if(i==3){break}
    document.write("The number is " + i)
    document.write("<br />")
  i=i+1
}

continue

The continue command will break the current loop and continue with the next value.

Example: This code skips "The number is 3 because when i==3 it will continue to i=4"
var i=0
for (i=0;i<=10;i++){
  if (i==3){continue}
    document.write("The number is " + i)
    document.write("<br />")
  }
}

The "for...in" statement

The for...in statement is used to loop (iterate) through the elements of an array or through the properties of an object.The code in the body of the for ... in loop is executed once for each element/property.

Syntax: for (variable in object){code to be executed}

The variable argument can be a named variable, an array element, or a property of an object.

Example: (Using for...in to loop through an array)

var x
var mynames = new Array()
mynames[0] = "Harry"
mynames[1] = "Roland"
mynames[2] = "Kunz"

for (x in mynames){
   document.write(mynames[x] + "<br />")
}
RESULT:

Events

Events are actions that can be detected by JavaScript.


Every element on a web page has certain events which can trigger JavaScript functions. 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:

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 and onMouseOut

onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected:

<a href="http://www.w3schools.com"
onmouseover="alert('An onMouseOver event');return false">
<img src="w3schools.gif" width="100" height="30"></a>

The "try...catch" Statement

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


There are two ways of catching errors in a Web page:

Syntax:
try{
  //Run some code here
}

catch(err){
  //Handle errors here. err is the variable
}

The function called by the button is given below:
    function try_catch(){
      var txt=""
      try{
        adddlert("Welcome guest!")
        //alert wrong spelling is intended to demonstrate the try...catch block.
      }
      catch(err){
        txt="There was an error on this page.(wrong spelling: 'adddlert')\n\n"
        txt+="Click OK to continue viewing this page,\n
              or Cancel to return to the home page."
        if(!confirm(txt)){
          document.location.href="http://www.w3schools.com/"
        }
      }
    }

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.

The button prompts a valid input.


  function throw_funct(){
    var x=prompt("Enter a number between 5 and 10:","")
    try{ 
      if(x>10) throw "Err1" 
      else if(x<-10) throw "Err2"
      else if(isNaN(x)) throw "Err3"
    }
    catch(er){
      if(er=="Err1") alert("Error! The value is too high")
      if(er == "Err2") alert("Error! The value is too low") 
      if(er == "Err3") alert("Error! The value is not a number") 
    }
  }

The onerror Event

*Using the onerror event is the old standard solution to catch errors in a web page.
*The onerror event is fired whenever there is a script error in the page.

To use the onerror event, you must create a function to handle the errors.
Then you call the function with the onerror event handler.
The event handler is called with 3 arguments:
msg (error message)
url (the url of the page that caused the error)
line (the line where the error occurred).

Syntax: (in <head><JScript>)
onerror = handleErr
function handleErr(msg,url,line){
  //Handle the error here
  return true/false
}

The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message.


<script type="text/javascript">
onerror = handleErr
var txt=""

function handleErr(msg,url,line){
  txt="There was an error on this page.\n\n"
  txt+="Error: " + msg + "\n"
  txt+="URL: " + url + "\n"
  txt+="Line: " + line + "\n\n"
  txt+="Click OK to continue.\n\n"
  alert(txt)
  return true/false
}

function message(){
  adddlert("Welcome guest! Wrong SPelling")
}
</script>
</head>

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

Special Characters

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


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
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

JScript Guidelines