You are on page 1of 81

Learning JavaScript Programming by Example 0

Joseph Ciriaco Ribo


Learning
JavaScript Programming
Learning JavaScript Programming by Example 1

By Example

JavaScript Introduction1

JavaScript Is

1. JavaScript is a scripting language that allows you to add functionality to your


Web pages by inserting code within an HTML document (since its initial release in
1995, JavaScript has become the most widely used programming language in
the world).

2. JavaScript can enhance a web page by adding items such as scrolling messages,
animations and dynamic images, data input forms, pop-up windows, and
interactive quizzes.

3. JavaScript is a product of a joint venture between Sun Microsystems and


Netscape Communications Corporation.

4. JavaScript is an open language that anyone can use without purchasing a


license.

5. JavaScript is an interpreted language, meaning that you do not have to compile


programs written with JavaScript before you can run them (It does not end up as
an executable file, instead, the code runs only on a JavaScript interpreter built
into your browser).

6. JavaScript programs can be embedded into Web pages or saved in separate


plain text-files.

7. JavaScript is supported by recent browsers from Netscape and Microsoft.


Because Internet Explorer supports additional features, Microsoft calls its version
JScript.

8. JavaScript version depends on the version of your browser because the


interpreter is a built-in feature of the browser.

9. JavaScript and Java share a few basic syntax rules like case sensitivity.

10.JavaScript is not a simplified version of Java.

1
Reference: http://www.w3schools.com
Reference: Cashman, T.,Shelly G., Dorin, W. Quasney, J.(2001). JavaScript Complete Concepts and
Techniques Second Edition. Course Technology. Canada

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 2

JavaScript How to

1. The HTML <script> tag is used to insert a JavaScript into an HTML page. Use
type attribute to define the scripting language, then the JavaScript starts. The
<script> tag has to be closed.

2. With traditional programming languages, like C++ and Java, each code
statement has to end with a semicolon. But semicolons are optional in
JavaScript. However, semicolons are required if you want to put more than one
statement on a single line.

3. Browsers that do not support scripts will display the script as page content. To
prevent then from doing this, use the HTML comment tag:

<script type=text/javascript>
<!
Some statements
//-->
</script>

4. The two forward slashes at the end of comment line (//) are a JavaScript
comment symbol. This prevents the JavaScript compiler from compiling the line.
You cannot put // in front of the first comment line (like //<!--), because older
browsers will display it.

JavaScript Where to

1. Script in the head section. Scripts to be executed when they are called, or
when an event triggered, go in the head section. When you place a script in the
head section, you will ensure that the script is loaded before anyone uses it.

2. Script in the body section. Scripts to be executed while the page loads go in
the body section. When you place a script in the body section it generates the
content of the page.

3. Scripts in both the body and the head section. You can place an unlimited
number of scripts in your document, so you can have scripts in both the body
and the head section.

4. External JavaScript. Sometimes you might want to run the same script on
several pages, without writing the script on each and every page. To simplify
this you can write a script in an external file, and save it with a .js file extension.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 3

Note: the external script cannot contain the <script> tag. You can call the
script, using src attribute, from any of your pages. Remember to place the script
exactly where you normally would write the script.

Example 1
Script in the head section.
Using document.write() function

HTML File:
Filename: Intro1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 4

Example 2
Script in the body section.

HTML File:
Filename: Intro2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 5

Example 3
Script in both the body and the head section.

HTML File:

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 6

Filename: Intro3.html

Example 4
External JavaScript.

HTML File:
Filename: Intro4.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 7

JAVASCRIPT File:
Filename: Task1.js

Example 5
How to format the text on your page with HTML tags.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 8

HTML File:
Filename: Intro5.html

Example 6
Using window.alert dialog box.
Using window.prompt dialog box.
Using JavaScript Variables.
Using JavaScript Arithmetic and Assignment Operators.
Using parseInt/parseFloat function

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 9

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 10

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 11

HTML File:
Filename: Intro6.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 12

The javascript: Pseudo-URL

1. Navigator and Internet Explorer 5.0 let you evaluate JavaScript statements that
you enter into the Location (Address) field. To tell the browser that what you
are entering is JavaScript code and not a URL, you must precede the statements
with the javascript: identifier. This identifier is called the JavaScript pseudo-
URL, as it is not a real URL.

2. Separate multiple statements with semi-colons and press Enter when youre done
to cause the browser to interpret your code.

Example 7
Using javascript: Pseudo-URL.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 13

JavaScript Control Statements2

Control statements give you control over the flow of your programs. You can create
loops or conditional statements. Conditional statements in JavaScript are used to
perform different actions based on different conditions.

JavaScript Conditional Statements

In JavaScript we have three conditional statements:

if statement use this if you want to execute a set of code when a condition is
true.

ifelse statement use this statement if you want to select one of two sets of
lines to execute.

switch statement use this statement if you want to select one of many sets of
lines to execute.

Conditional operator - JavaScript also contains a conditional operator that assigns


a value to a variable based on some condition. It is the only ternary operator in
JavaScript, that is, it is the only operator that takes three operands. Because of this,
the conditional operator is sometimes called the ternary operator.

Syntax:
condition ? expression if true : expression if false

variableName = condition ? value if true : value if false

Examples:
X ==100 ? alert(x is 100) : alert(x is not 100)

var z = (x==10) ? Equal : Not Equal

2
Reference: http://www.w3schools.com

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 14

Example 1
Using JavaScript if Selection Statements.
Using JavaScript Comparison Operators.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 15

HTML File:
Filename: Control1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 16

Example 2
Using JavaScript if/else Selection Statements.
Using window.confirm() dialog box.
Using window.close() function.

If the user has clicked on Ok button:

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 17

If the user has clicked on Cancel button:

HTML File:
Filename: Control2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 18

Example 3
Using JavaScript conditional/ternary operator.

HTML File:
Filename: Control3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 19

Example 4
Using JavaScript switch statement.

HTML File:
Filename: Control4.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 20

JavaScript Looping Statements3

In JavaScript we have three looping statements:


for loops these loops repeat a block of statements until a condition you specify
is no longer met.

while loops these loops repeat as long as a condition is true rather than false.

do/while loops loops through a block of code once, and then repeats the loop
while a condition is true.

Example 5
Using JavaScript while loops(counter-controlled repetition).

HTML File:
Filename: Control5.html

3
Reference: http://www.w3schools.com

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 21

Example 64
Using JavaScript while loops (sentinel-controlled repetition).

4
Reference: Deitel, H, Deitel, H, Nieto T.(2001). E-Business & e-Commerce How to Program. Prentice
Hall. USA

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 22

HTML File:
Filename: Control6.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 23

Example 7
Using JavaScript for loops.

HTML File:
Filename: Control7.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 24

Example 8
Using JavaScript do/while loops.

HTML File:
Filename: Control8.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 25

JavaScript Functions5

1. Function is a way to write several lines of script and use them repeatedly as
needed. You define functions at the beginning of a file (head section), and call
them later in the document.

2. By placing functions in the head section of the document, you make sure that all
the code in the function has been loaded before the function is called.

3. To create a function you define its name, any values (arguments), and some
statements.
Example:

function myFunction(a, b)
{
Some statements;
}

4. A function with no arguments must include the parentheses.


Example:

function myFunction()
{
Some statements;
}

5. Some functions return a value to the calling expression. Functions that will
return a result must use the return statement. This statement specifies the
value which will be returned to where the function was called from.
Example:

function result(a,b) //function Definition


{
c = a + b;
return c;
}

Sum = result(4,5); // function call

6. A function is not executed before it is called. You can call a function containing
arguments or without arguments.
Example:

function MyFunction(x,y);
function MyFunction();

5
Reference: http://www.w3schools.com

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 26

Example 1
Function without arguments.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 27

HTML File:
Filename: Function1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 28

Example 2
Function with arguments.

HTML File:
Filename: Function2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 29

Example 3
Function that returns a value.

HTML File:
Filename: Function3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 30

Example 4
Function with arguments that return a value.

HTML File:
Filename: Function4.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 31

Example 56
Calling Functions from tags. One of the benefits of JavaScript is to be able to tie
interactivity to elements of the HTML page. One way you can do this is to set up
links in HTML that actually triggers calls to JavaScript functions when the link is
clicked.

Using onClick Event Handler. onClick is an event handler; this means it specified
JavaScript code to execute when an event occurs. In this case, the event that must
occur is the click event: The user must click on the link.

HTML File:
Filename: Function5.html

6
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 32

Example 67
Calling Functions After The Page Has Loaded. Sometimes you will want to
execute JavaScript code only once the HTML page has fully loaded.

Using onLoad event Handler. onLoad is an event handler; this means it specified
JavaScript code to execute when an event occurs. In this case, the event that must
occur is the completion of loading of the document.

HTML File:
Filename: Function6.html

7
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 33

Example 78
Calling Functions when the user tries to leave the page. Sometimes you will
want to execute JavaScript code only when the user tries to leave your page. You
might want to do this because you want to bid the user farewell or remind the user
he or she is leaving your site.

Using onUnLoad event Handler. onUnLoad is an event handler; this means it


specified JavaScript code to execute when an event occurs. In this case, the event
that must occur is the user navigating to another page. Try to close your browser
window or navigate to another site and you should see the alert box.

HTML File:
Filename: Function7.html

8
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 34

Example 89
Scheduling a Function for Future Execution. Sometimes you will want to
execute a function in an automated, scheduled way. JavaScript provides the ability
to schedule execution of a function at a specified time in the future. When the
appointed time arrives, the function automatically executes without user
intervention.
Using window.setTimeout method. Scheduling is done with the
window.setTimeout method. The function to execute is specified as if you were
calling the function normally but in a text string; the text string contains the actual
text of the command to execute. The schedule time specifies the number of
milliseconds to wait before executing the function. For instance, if you want to wait
10 seconds before executing the function, you need to specify 10000 milliseconds.

HTML File:
Filename: Function8.html

9
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 35

Example 910
Scheduling a Function for Recurring Execution. What if you wanted to schedule
the same function to execute at set intervals? In the example below, the alert dialog
boxes will appear every five seconds indefinitely. To go out of this, simply close the
browser window in one of the intervals between dialog boxes.

HTML File:
Filename: Function9.html

10
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 36

Example 1011
Canceling a Scheduled Function. Using related method, window.clearTimeout,
you can cancel a scheduled execution event before it occurs. When you create a
scheduled event, the window.setTimeout method returns a pointer to that event.
You can then use the pointer to cancel the scheduled event. You simply pass that
pointer to window.clearTimeout.

Note: Just why would you want to cancel a scheduled function call? There are a
number of reasons. For instance, you may want to use the scheduled function as a
form of countdown. The user, for instance, may have a certain number of seconds
to perform a task on the page before the page is cleared. You can schedule a
function call to clear the page and then cancel it if the user performs the desired
action.

If you open the sample file in a browser nothing should appear except a blank
browser window.

HTML File:
Filename: Function10.html

11
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 37

Example 11
JavaScript Functions with HTML Forms

HTML File:
Filename: Function11.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 38

JavaScript Math Object

Math objects methods allow the programmer to perform many common


mathematical calculations. Some of the most commonly used Math methods are the
following:

Methods Description Examples

Math.abs(x) Absolute value of x. Math.abs(7.2) = 7.2


Math.abs(0.0) = 0.0
Math.abs(-5.6) = 5.6

Math.ceil(x) Rounds x to the smallest integer not Math.ceil(9.2) = 10


less than x. Math.ceil(-9.8) = -9

Math.floor(x) Rounds x to the largest integer not Math.floor(9.2) = 9


greater than x. Math.floor(-9.8)= -10

Math.max(x,y) Larger value of x and y. Math.max(2.3, 12.7)


= 12.7

Math.min(x,y) Smaller value of x and y. Math.min(2.3, 12.7)


= 2.3

Math.pow(x,y) X raised to the power y. (XY) Math.pow(2,3) = 8

Math.round(x) Rounds x to the closest integer. Math.round(9.75)


= 10

Math.round(9.45)
=9

Math.sqrt(x) Square root of x. Math.sqrt(9) = 3

Math.random() A random number between 0.0 and n = Math.random()


1.0 (but not including 1.0)

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 39

Example 1
Using Math.random() method

HTML File:
Filename: Math1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 40

JavaScript Array Object12

1. An array object is used to store a set of values in a single variable name. Each
value is an element of the array and has an associated index number.

2. You can refer to a particular element in the array by using the name of the array
and the index number. The index number starts at zero.

3. You create an instance of the Array object with the new keyword. The
expected number of elements goes inside the parentheses.
Example:
1. To allocate 5-element Array:

var a = new Array(5);

2. To allocate empty Array:

var a = new Array();

3. If an Arrays element values are known in advance, the elements of


the Array can be allocated and initialized in the array declaration.
Note the following declaration does not require the new operator to
create the Array object this is provided by the interpreter when it
encounters an array declaration that includes an initializer list13:

var a =[10, 20, 30, 40, 50];

4. It is also possible to reserve a space in an Array for a value to be


specified later by using a comma as place holder in the initializer list:

var a =[10, 20, , 40, 50];

5. It is also possible that the array size is determined by the number of


values in parentheses. The following example creates a five-element
array with subscripts of 0, 1, 2, 3 and 4.

var a = new Array(10, 20, 30, 40, 50);

4. You assign data to each of the elements in the array by using the index of the
particular array element you want.
Example:
1. a[0] = Joseph
2. a[1] = Ribo

5. You retrieved data from any element in the array by using the index of the
particular array element you want.
Example:
1. var b = a[1];
12
Reference: http://www.w3schools.com
13
Reference: Deitel, H, Deitel, H, Nieto T.(2001). E-Business & e-Commerce How to Program. Prentice
Hall. USA

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 41

Example 1
Displaying a Random Image with length property. The length property of an
Array object provides the number of entries in an array. That means if an array has
four entries numbered 0 to 3, then the length property of that array has a value of
4.

HTML File:
Filename: Array1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 42

Example 2
Creating a Slide Show in JavaScript Manually. One popular use of JavaScript
with images is to create slide shows in HTML pages. This example allows the user to
move the slide show forward and backward by clicking on links.

HTML File:
Filename: Array2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 43

Example 3
Creating a Slide Show in JavaScript Automatically. This example illustrates the
creation of an automatic slide show in which the image transitions happen every two
seconds.

HTML File:
Filename: Array3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 44

Example 4
Creating a Slide Show in JavaScript Automatically (with Blend Transition).

HTML File:
Filename: Array4.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 45

JavaScript Date Object14

1. Date object provides methods for date and time manipulations. You create an
instance of the Date object with the new keyword.
Example:
var thisDate = new Date();

2. After creating an instance of the Date object, you can access all the methods of
the object from thisDate variable. Some of the most commonly used Date
methods are the following:

Methods Description

getHours() Returns a number from 0 to 23 representing hours.

getMinutes() Returns a number from 0 to 59 representing minutes.

getSeconds() Returns a number from 0 to 59 representing seconds.

getMilliseconds() Returns a number from 0 999.

getDay() Returns a number from 0 to 6 representing the day of


the week.

getMonth() Returns a number from 0 to 11 representing the


month.

getDate() Returns a number from 1 to 31 representing the day


of the month.

getFullYear() Returns the year as a four digit number in local time.

toString() Returns the current date and time in a standard


format as a string. You dont have any direct control of
that formatting.

toLocaleString() Returns the time as a string using the date formatting


conventions of the current locale.

toUTCString() Returns the time as a string converted to Universal


Time. UTC stands for Universal Time Coordinate.
toGMTString() UTC is the same as Greenwich Mean Time but has
become the preferred name for this default standard
time zone.

14
Reference: http://www.w3schools.com

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 46

Example 1
Outputting the Date to the Browser. This example displays and controls the
format of the current date and time within a page using toString(),
toLocaleString(), toUTCString(), and toGMTString() methods.

HTML File:
Filename: Date1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 47

Example 2
Using getDate(), getMonth(), getFullYear() and getDay() methods. This
example returns todays date including date, month, and year as well as the day of
the week. Note that the getMonth method returns 0 in January, 1 in February etc.
So add 1 to the getMonth method to display the correct date.

HTML File:
Filename: Date2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 48

Example 3
Using getHours(), getMinutes(), getSeconds() and getMilliseconds()
methods.This example demonstrates how to display the military time on web pages.

HTML File:
Filename: Date3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 49

JavaScript String Object15


String object is used to work with text. Some of the most commonly used String
objects properties and methods are described below:

Properties Description

length Returns a number of characters in a string.

Methods Description

charAt(index) Returns the character at a specified position.

concat (string) Returns two concatenated strings.

indexOf(substring) Returns the position of the first occurrence of a


specified string inside another string. Returns
indexOf(substring, index) -1 if it never occurs.

lastIndexOf(substring, index) Returns the position of the first occurrence of a


specified string inside another string. Returns
-1 if it never occurs.

Note: This method starts from the right and


moves left.

match(string) Similar to indexOf() and lastIndexOf(), but


this method returns the specified string, or
null, instead of a numeric value.

search(string) Returns an integer if the string contains some


specified characters, if not it returns -1.

slice(start, end) Returns a string containing a specified


character index.

15
Reference: http://www.w3schools.com

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 50

strike() Returns a string strikethrough.

sub() Returns a string as subscript.

sup() Returns a string as superscript.

substr(start, length) Returns the specified characters. 14, 7 returns


7 characters, from the 14th character (starts at
0).

substring(start, end) Returns the specified characters. 7, 14 returns


all characters from the 7th up to but not
including the 14th (starts at 0).

toLowerCase() Converts a string to lower case.

toUpperCase() Converts a string to upper case.

toString() Returns the same string as the source string.

valueOf() Returns the same string as the source string.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 51

Example 1
Using length property and charAt(), concat(), indexOf(), lastIndexOf(),
match() and search() methods.

HTML File:
Filename: String1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 52

Example 2
Using slice(),substr(),substring(),strike(),sub(), sup(),toLowerCase(),
toUpperCase(),toString() and valueOf() methods.

HTML File:
Filename: String2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 53

Example 3
Scrolling Messages using subString() method

HTML File:
Filename: String3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 54

JavaScript Window Object16

1. Window object is the top level object in the hierarchy. By using the various
properties and methods associated with the window object, you can manipulate
your document. In the example below, the Document object was used with the
write() method:
document.write(hello);

the statement could have been written as:

window.document.write(hello);

because of the hierarchy of the JavaScript object, the Window object is assumed.

2. Window object provides access to properties and methods that can be used
to obtain information about open windows, as well as to manipulate these
windows and even open new windows.

3. Window object offers properties that allow you to access frames in a window,
access the windows name, manipulate text in the status bar, and check the open
or closed state of the window.

4. Window object offers methods that allow the user to display a variety of dialog
boxes, as well as to open new windows and close open windows.

5. Window object can be referred to in several ways:

Using the keyword window or self to refer to the current window where the
JavaScript code is executing. For instance, window.alert and self.alert refer
to the same method.

Using the object name for another open window. For instance, if a window is
associated with an object named myWindow, myWindow.alert would refer
to the alert method in that window.

6. The most commonly used Window object properties and methods are the
following:

Methods Description

alert() Displays an alert box with a message and an


OK button.

confirm() Displays a confirm box with a message, a


Cancel and an OK button.

prompt() Displays a prompt box with a message and an


input field.

16
Reference: http://www.w3schools.com , Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or
Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 55

open() Opens a new window.

close() Closes the current window.

reload() Refresh the current document.

print() Print the windows document.

Property Description

status Sets or returns the message in the status bar.

document Returns the document object.

location Returns the current URL.

Window Features
You can set features (or decorations, as they are sometimes called) for your new
windows using optional parameters of the window.open() method. In JavaScript,
window features are the buttons, toolbars, and even the dimensions of the window.
When you open a window with window.open(), you can specify whatever features
you would like:
Window feature Description

height Specifies the height of the document area of


the window in pixels.
width Specifies the width of the document area of the
window in pixels.
location Specifies whether to display the address field,
in which users can enter new URLs.
menubar Specifies whether to display the menu bar.

scrollbars Specifies whether to display horizontal and


vertical scroll bars when they are necessary.

resizable Specifies whether to permit the user to resize


the window.

status Specifies whether to display the status bar.

toolbar Specifies whether to display the toolbar.

top Specifies the location of a new window from the


top of the screen.
left Specifies the location of a new window from the
left of the screen.
fullScreen Specifies whether to open a full-screen window.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 56

Example 1
Opening a New Browser Window. The window object provides the open method,
which can be used to open a new browser window and display a URL in that window.
In its most basic form, the open method works as follows:
window.open(url, window name);
The window.open method can actually take one argument, two arguments or three
arguments. For basic use, one or two arguments suffice. Advanced use such as
controlling the size of a window when it opens relies on a third argument. This task
illustrates basic use of the method.
Notice the use of # as the URL in the example. When using the onClick event
handler to trigger the opening of a new window, you dont want to cause clicking on
the link to change the location of the current window; this is a simple way to avoid
this.

Opening a new window when the user clicks the link or button

HTML File:
Filename: Window1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 57

Example 2
Setting the size of New Browser Windows. To control the size of the window,
you need to set the height and the width property values by assigning a number of
pixels to each of them.

HTML File:
Filename: Window2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 58

Example 3
Setting the Location & Controlling the Appearance of a New Browser
Windows.

HTML File:
Filename: Window3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 59

Example 4
Opening a Full-Screen Window in Internet Explorer

HTML File:
Filename: Window4.html

Example 5

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 60

Using reload, location, print(),close(),and status() methods. This example


demonstrates how to send the client to a new location, how to refresh and print a
document, how to close a window and how to write some text in the windows status
bar.

HTML File:
Filename: Window5.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 61

JavaScript Form Object17

In JavaScript, you can access and manipulate the content and state of fields in forms
on the page. To do this, you need to give some attention to the minimum
requirements needed to make your forms easily accessible in JavaScript. Primarily,
you must focus on providing names for your forms and elements.

Example of a JavaScript-ready form:

<body>
<form name=thisForm method=post action=target.html>
<input type=text name=myText>
<select name=mySelect>
<option value=1> First Choice </option>
<option value=2> Second Choice </option>
</select>
<br/>
<input type=submit value=Submit Me>
</form>
</body>

Notes:

1. To access a field in a form, you can use the following reference in JavaScript:

document.forms[0].elements[0]

Each form in your document is contained in the forms array in the order it appears in
your document. The elements array, similarly, has one entry for each field in a given
form in the order the fields appear in the form.

2. If the form is not named, then each form is accessible in the document.forms
array, so that the first form in the document is document.forms[0], the second
is document.forms[1], and so on.

3. If the field is not named, then each field in the form is accessible in the
document.formName.elements array, so that the first field in the form is
document.formName.elements[0], the second is
document.formName.elements[1], and so on.

Tips:

1. Naming fields and forms makes them much easier to refer to and ensures you
are referring to the correct fields in your code.

2. When naming forms and the elements within your forms, you should use
descriptive names.

17
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 62

Example 1
Accessing Text Field Contents & Dynamically Updating Text Fields. This
example shows you how to access a field in JavaScript and how to dynamically
update the text that is displayed in a text input field.

HTML File:
Filename: Form1.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 63

Example 2
Accessing Selection Lists. This example shows you how to check the current
selection in a selection list.

HTML File:
Filename: Form2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 64

Example 3
Detecting Selections in Selection Lists. This example shows you how to react to
the user selecting option in a selection list that was created with the select tag. You
can specify code to execute when a selection occurs in the field with the onChange
event handler.

HTML File:
Filename: Form3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 65

Example 4
Detecting the Selected Radio Button. This example shows you how to check
which radio button the user has selected.

HTML File:
Filename: Form4.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 66

Example 5
Detecting Change of Radio Button Selection. This example shows you how to
react to the user selecting a new radio button.

HTML File:
Filename: Form5.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 67

Example6
Updating or Changing Radio Button Selection. This example shows you how to
select a radio button in a group of radio buttons.

HTML File:
Filename: Form6.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 68

Example7
Detecting Check Box Selections. This example shows you how to check selection
status of a check box.

HTML File:
Filename: Form7.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 69

Example8
Changing Check Box Selections. This example shows you how to control selection
status of a check box.

HTML File:
Filename: Form8.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 70

Example9
Detecting Changes in Check Box Selections. This example shows you how to
react to the user clicking on a check box.

HTML File:
Filename: Form9.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 71

Example10
Verifying Form Fields in JavaScript. This example shows you how to check the
data entered in a field when the user attempts to move out of the field. Until valid
data is entered, you prevent the user from leaving the field.
Notes:
1. This process relies on the focus method available for form field objects. This
method sets mouse focus into a field that did not have focus before.
2. The field that has focus is the field that is currently active. A field is often
given focus when the user clicks on it or tabs to it. In this task you see how to
force the focus to go to a specific field.
3. Notice that this is passed as the argument to the check function. In the event
handlers for a form field, this refers to the object for the form itself.

HTML File:
Filename: Form10.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 72

Example11
Using Graphical Buttons in JavaScript. This example lets you place images
within a form as elements.

HTML File:
Filename: Form11html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 73

JavaScript Dynamic User Interaction

With JavaScript you can create dynamic user interfaces. One interface is a pull-down
menu that might initially appear closed in a Web page. But when the user moves the
mouse pointer over the menu, the pull-down menu appears.

Notice the use of the conditional based on document.getElementById. In Internet


Explorer, this method is available, and you use it to access the style property of the
target object.

Example1
Creating a Simple Pull-Down Menu. This example outlines how to build an
extremely simple pull-down menu.

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 74

HTML File:
Filename: Dynamic1html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 75

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 76

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 77

Example2
Creating a Sliding Menu. This example outlines how to create a menu that slides
into view when it is needed and then is hidden when it is not needed.

HTML File:
Filename: Dynamic2.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 78

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 79

Example3
Sliding Menus.

HTML File:
Filename: Dynamic3.html

Joseph Ciriaco Ribo


Learning JavaScript Programming by Example 80

Joseph Ciriaco Ribo

You might also like