JavaScript 1

Reference: W3Schools

What is JavaScript?

 

Are Java and JavaScript the Same?

 

What can a JavaScript Do?

 

JavaScript How To ...

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

How to Put a JavaScript Into an HTML Page

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

helloworld.html

Note: document.write is a standard JavaScript command for writing output to a page.

·        By entering the document.write command between the <script type="text/javascript"> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page:

Ending Statements With a Semicolon?

·        With traditional programming languages, like C++ and Java, each code statement must end with a semicolon.

·        In JavaScript semicolons are optional!

·        However, semicolons are required if you want to put more than one statement on a single line.

Where to Put the JavaScript

Scripts in the head section:

Executed :

·        when they are called

·        when an event is triggered

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

Scripts in the body section:

Executed when:

·        the page loads

·        these scripts generate the content of the page.

<html>
<head>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>
</html>

Scripts in both the body and the head section:

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>
</html>

 

Using an External JavaScript

·        Can write a JavaScript in an external file

·        Save the external JavaScript file with a .js file extension.

·        Note: The external script cannot contain the <script> tag!

·        To use the external script, point to the .js file in the "src" attribute of the <script> tag:

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

 

JavaScript Variables

Variables

·        A variable is a "container" for information you want to store.

·        A variable's value can change during the script.

·        You can refer to a variable by name to see its value or to change its value.

 

Rules for variable names:

IMPORTANT! JavaScript is case-sensitive! A variable named strname is not the same as a variable named STRNAME!

Declare a Variable

You can create a variable with the var statement:

var strname = some value

 

You can also create a variable without the var statement:

strname = some value

 

Assign a Value to a Variable

You can assign a value to a variable like this:

var strname = "Hege"

 

Or like this:

strname = "Hege"

 

Example : variable_ex.html

<html>

<body>

 

<script type="text/javascript">

var name = "Hege"

document.write(name)

document.write("<h1>"+name+"</h1>")

</script>

 

<p>This example declares a variable, assigns a value to it, and then displays the variable.</p>

 

<p>Then the variable is displayed one more time, only this time as a heading.</p>

 

</body>

</html>

 

This example declares a variable, assigns a value to it, and then displays the variable.

Then the variable is displayed one more time, only this time as a heading.

 

 

Conditional Statements

If Statement

Syntax

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

 

if statement Results

Condition

returns true if

x == y

x and y are equal

x != y

x and y are not equal

x > y

x is greater than y

x >= y

x is greater or equal to y

x < y

x is less than y

x <= y

x is less than or equal to y

Example 1

if_ex.html

<html>

<body>

 

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

 

if (time > 10)

{

document.write("<b>Good Afternoon</b>")

}

</script>

 

<br>

<p>

This example demonstrates the If statement.

</p>

 

<p>

If the time on your browser is greater than 12,

you will get a "Good Afternoon" greeting.

</p>

 

</body>

</html>

 

This example demonstrates the If statement.

If the time on your browser is greater than 12, you will get a "Good Afternoon" greeting.

 

 

If...else Statement

Syntax

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

Example

<html>

<body>

 

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

 

if (time < 10)

{

document.write("<b>Good morning</b>")

}

else

{

document.write("<b>Good day</b>")

}

</script>

 

<p>

This example demonstrates the If...Else statement.

</p>

 

<p>

If the time on your browser is less than 10,

you will get a "Good morning" greeting.

Otherwise you will get a "Good day" greeting.

</p>

 

</body>

</html>

 

This example demonstrates the If...Else statement.

If the time on your browser is less than 10, you will get a "Good morning" greeting. Otherwise you will get a "Good day" greeting.

 

 

 

If...else if...else Statement

Syntax

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 condition1 and
condition2 are not true
}

Example

<html>

<body>

 

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

if (time<10)

{

document.write("<b>Good morning</b>")

}

else if (time>=10 && time<16)

{

document.write("<b>Good day</b>")

}

else

{

document.write("<b>Hello World!</b>")

}

</script>

 

<p>

This example demonstrates the if..else if...else statement.

</p>

 

</body>

</html>

 

 

This example demonstrates the if..else if...else statement.

 

 

The JavaScript Switch Statement

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

Syntax

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
}

·        n (most often a variable) 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.

Example

<html>

<body>

<script type="text/javascript">

var d = new Date()

theDay=d.getDay()

switch (theDay)

{

case 5:

  document.write("<b>Finally Friday</b>")

  break

case 6:

  document.write("<b>Super Saturday</b>")

  break

case 0:

  document.write("<b>Sleepy Sunday</b>")

  break

default:

  document.write("<b>I'm really looking forward to this weekend!</b>")

}

</script>

 

<br>

 

<p>This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>

 

</body>

</html>

 

This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.

 

 

JavaScript Operators

Arithmetic Operators

Operator

Description

Example

Result

+

Addition

x=2
y=2
x+y

4

-

Subtraction

x=5
y=2
x-y

3

*

Multiplication

x=5
y=4
x*y

20

/

Division

15/5
5/2

3
2.5

%

Modulus (division remainder)

5%2
10%8
10%2

1
2
0

++

Increment

x=5
x++

x=6

--

Decrement

x=5
x--

x=4

Assignment Operators

Operator

Example

Is The Same As

=

x=y

x=y

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

%=

x%=y

x=x%y

Comparison Operators

Operator

Description

Example

= =

is equal to

5= =8 returns false

= = =

is equal to (checks for both value and type)

x=5
y="5"

x==y returns true
x===y returns false

!=

is not equal

5!=8 returns true

>

is greater than

5>8 returns false

<

is less than

5<8 returns true

>=

is greater than or equal to

5>=8 returns false

<=

is less than or equal to

5<=8 returns true

Logical Operators

Operator

Description

Example

&&

and

x=6
y=3

(x < 10 && y > 1) returns true

||

or

x=6
y=3

(x==5 || y==5) returns false

!

not

x=6
y=3

!(x==y) returns true

String Operator

·        A string is most often text, for example "Hello World!".

·        To append two or more string variables together, use the + operator.

txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2 

The variable txt3 now contains "What a verynice day!".

 

To add a space between two string variables, insert a space into the expression, OR in one of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
 
or
 
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename=(condition)?value1:value2 

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear "

·        If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting.

·        If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

 

JavaScript Popup Boxes

JavaScript can create three kinds of popup boxes:

·        Alert box

·        Confirm box

·        Prompt box

 

Alert Box

·        An alert box is often used 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")


alertboxex.html

<html>

<head>

<script type="text/javascript">

function disp_alert()

{

alert("I am an alert box!!")

}

</script>

</head>

 

<body>

<form>

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

</form>

</body>

 

</html>

 

 

Confirm Box

·        A confirm box is used for verification.

·        When a confirm box pops up, the user must 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

Confirmboxex.html

<html>

<head>

<script type="text/javascript">

function disp_confirm()

{

var name=confirm("Press a button")

if (name==true)

{

document.write("You pressed the OK button!")

}

else

{

document.write("You pressed the Cancel button!")

}

}

</script>

</head>

 

<body>

<form>

<input type="button" onclick="disp_confirm()" value="Display a confirm box">

</form>

</body>

</html>

 

Prompt Box

·        A prompt box is used to input a value before entering a page.

·        When a prompt box pops up, the user must 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")

 

promptboxex.html

<html>

<head>

<script type="text/javascript">

function disp_prompt()

{

var name=prompt("Please enter your name","")

if (name!=null && name!="")

{

document.write("Hello " + name + "! How are you today?")

}

}

</script>

</head>

 

<body>

<form>

<input type="button" onclick="disp_prompt()" value="Display a prompt box">

</form>

</body>

 

</html>

 

JavaScript Functions

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

·        A function contains code that will be executed in response to an event or by a call to that function.

·        You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).

·        Functions are defined at the beginning of a page, in the <head> section.

Example

funcallex.html

<html>

<head>

 

<script type="text/javascript">

function myfunction()

{

alert("HELLO")

}

</script>

 

</head>

<body>

 

<form>

<input type="button"

onclick="myfunction()"

value="Call function">

</form>

 

<p>By pressing the button, a function will be called. The function will alert a message.</p>

 

</body>

</html>

 

 

 

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

·        var1, var2, etc are variables or values passed into the function.

·        The { and the } defines the start and end of the function.

Function Call With Arguments:

Funcallargex.html

<html>

<head>

 

<script type="text/javascript">

function myfunction(txt)

{

alert(txt)

}

</script>

 

</head>

<body>

 

<form>

<input type="button"

onclick="myfunction('Hello')"

value="Call function">

</form>

 

<p>By pressing the button, a function with an argument will be called. The function will alert

this argument.</p>

 

</body>

</html>

 

 

The return Statement

·        The return statement is used to specify the value that is returned from the function.

Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b
return x
}

 

Sample Call to this function:

product=prod(2,3)

The returned value from the prod() function is 6, and it will be stored in the variable called product

 

Funcallretex.html

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

<p>The script in the body section calls a function with two parameters (4 and 3).</p>

<p>The function will return the product of these two parameters.</p>

</body>

</html>

 

JavaScript Loops

Two types of loops:

 

The for Loop

Syntax

for (var=startvalue;var<=endvalue;var=var+increment) 
{
    code to be executed
}

 

Example

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

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

 

 

Combining for loop with function call

Funloopex.html

<html>

<head>

<script type="text/javascript">

function count(a,b)

{var i

for (i=a;i<=b;i++)

      {

      document.write("The number is " + i)

      document.write("<br />")

      }

return

}

</script>

</head>

 

<body>

<form>

<input type="button"

onclick="count(1,10)"

value="Start Counting">

</form>

</body>

</html>

 

 

The while loop

Used when you want the loop to execute and continue executing while the specified condition is true. 

while (var<=endvalue)
{
    code to be executed
}

Note: The <= could be any comparing statement.

 

Example

·        The example below defines a loop that starts with i=0.

·        The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

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

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

 

The do...while Loop

·        The do...while loop is a variant of the while loop.

·        This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

·        This loop will always be executed once, even if the condition is false, because the code is executed before the condition is tested.

do
{
    code to be executed
}
while (var<=endvalue)

Example

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

Result

The number is 0

 

JavaScript Events

Events are actions that can be detected by JavaScript.

Examples of events:

 

Event Handlers (from http://www.elated.com/tutorials/programming/javascript/events/# )

·         HTML 4.0 allows events to trigger actions in the browser

·         Below is a list of the attributes that can be inserted into HTML tags to define event actions.

·         All the event handlers in JavaScript start with the word on, and each event handler deals with a certain type of event.

·         Here's a list of all the event handlers in JavaScript, along with the objects they apply to and the events that trigger them:

 

Event Handler

Applies To:

Triggered When:

onAbort

Image

The loading of the image is cancelled.

onBlur

Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window

The object in question loses focus (e.g. by clicking outside it or pressing the TAB key).

onChange

FileUpload, Select, Text, TextArea

The data in the form element is changed by the user.

onClick

Button, Document, Checkbox, Link, Radio, Reset, Submit

The object is clicked on.

onDblClick

Document, Link

The object is double-clicked on.

onDragDrop

Window

An icon is dragged and dropped into the browser.

onError

Image, Window

A JavaScript error occurs.

onFocus

Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window

The object in question gains focus (e.g. by clicking on it or pressing the TAB key).

onKeyDown

Document, Image, Link, TextArea

The user presses a key.

onKeyPress

Document, Image, Link, TextArea

The user presses or holds down a key.

onKeyUp

Document, Image, Link, TextArea

The user releases a key.

onLoad

Image, Window

The whole page has finished loading.

onMouseDown

Button, Document, Link

The user presses a mouse button.

onMouseMove

None

The user moves the mouse.

onMouseOut

Image (NOT NS4), Link

The user moves the mouse away from the object.

onMouseOver

Image (NOT NS4), Link

The user moves the mouse over the object.

onMouseUp

Button, Document, Link

The user releases a mouse button.

onMove

Window

The user moves the browser window or frame.

onReset

Form

The user clicks the form's Reset button.

onResize

Window

The user resizes the browser window or frame.

onSelect

Text, Textarea

The user selects text within the field.

onSubmit

Form

The user clicks the form's Submit button.

onUnload

Window

The user leaves the page.

Using an Event Handler

To use an event handler, you usually place the event handler name within the HTML tag of the object you want to work with, followed by ="SomeJavaScriptCode", where SomeJavaScriptCode is the JavaScript you would like to execute when the event occurs.

For example:

onClick

 

<html>
<body>
 
<form>
<input type="button" name="clickme"
value="Click Me!" onClick="alert('Thank You!')">
</form>
 
</body>
</html>

 

 

Some Common Event Handlers

In this section, we'll look at a few of the more commonly used event handlers, and examine how they can be used.

onChange

·         onChange is commonly used to validate form fields (see tutorial on Form Validation with JavaScript) or to otherwise perform an action when a form field's value has been altered by the user.

·         The event handler is triggered when the user changes the field then clicks outside the field or uses the TAB key (i.e. the object loses focus).

This example code ensures that you type in both your first and your last names. It will bring up an alert box and refocus the text box field if you only type one word into the text box.

Please enter your name: <input type="text"
name="your_name" onChange=validateField(this)>
<script language="JavaScript">
function validateField ( fieldname )
{
    if ( ( fieldname.value ) &&
    ( ! fieldname.value.match ( " " ) ) )
    {
        alert ( "Please enter your first and last names!" );
        fieldname.focus ( );
    }
}
</script>

Please enter your name:

 

onFocus

·         onFocus is executed whenever the specified object gains focus.

·         This usually happens when the user clicks on the object with the mouse button, or moves to the object using the TAB key.

·         onFocus can be used on most form elements.

Example

This example text box contains the prompt Please enter your email address that is cleared once the text box has focus.

<
input type="text" name="email_address"
size="40" value="Please enter your email address"
onFocus="this.value=''">

 

onKeyPress

·         You can use onKeyPress to determine when a key on the keyboard has been pressed.

·         This is useful for allowing keyboard shortcuts in your forms and for providing interactivity and games.

Example

·         This example uses the onKeyPress event handler for the Window object to determine when a key was pressed.

·         In addition, it uses the which property of the Event object to determine the ASCII code of the key that was pressed, and then displays the pressed key in a text box.

·         If event.which is undefined it uses event.keyCode instead (Internet Explorer uses event.keyCode instead of event.which).

<html>
<body onKeyPress = "show_key(event.which)">
<form method="post" name="my_form">
The key you pressed was:
<input type="text" name="key_display" size="2">
</form>
<script language="JavaScript">
function show_key ( the_key )
{
    if ( ! the_key )
    {
        the_key = event.keyCode;
    }
    document.my_form.key_display.value
    = String.fromCharCode ( the_key );
}
</script>
</body>
</html>

Click here to try it out in a new window!

 

onLoad

·         The onLoad event handler is triggered when the page has finished loading.

·         Common uses of onLoad include the dreaded pop-up advertisement windows, and to start other actions such as animations or timers once the whole page has finished loading.

·         Example

This simple example displays an alert box when the page has finished loading:

 
<html>
<body onLoad = "alert('Thanks for visiting my page!')">
My Page
</body>
</html>

Click here to try it out in a new window!

 

onMouseOut, onMouseOver

The classic use of these two event handlers is for JavaScript rollover images

Example

Here's a simple example that alters the value of a text box depending on whether the mouse pointer is over a link or not.

<html>
<body>  
<form name="first_form">
    <input type="text" name="first_text" value="  ">
   
<a href="" onMouseOver="window.document.first_form.first_text.value='Over Text';" 
onMouseOut="window.document.first_form.first_text.value='NOT Over text'">Put Mouse Over Here</a>
 
</form> 
</body>
</html>

Mouseexb.html

 

Example: Highlighted Menu

Mousemenu.html

 

Pace University

School Computer Science and Information Systems

Center for Advanced Media

Pace Digtial Gallery

Dr. Francis T. Marchese