Javascript by Example
Javascript by Example
By Example
JavaScript Introduction1
JavaScript Is
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.
9. JavaScript and Java share a few basic syntax rules like case sensitivity.
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
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.
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
Example 2
Script in the body section.
HTML File:
Filename: Intro2.html
Example 3
Script in both the body and the head section.
HTML File:
Filename: Intro3.html
Example 4
External JavaScript.
HTML File:
Filename: Intro4.html
JAVASCRIPT File:
Filename: Task1.js
Example 5
How to format the text on your page with HTML tags.
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
HTML File:
Filename: Intro6.html
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.
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.
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.
Syntax:
condition ? expression if true : expression if false
Examples:
X ==100 ? alert(x is 100) : alert(x is not 100)
2
Reference: http://www.w3schools.com
Example 1
Using JavaScript if Selection Statements.
Using JavaScript Comparison Operators.
HTML File:
Filename: Control1.html
Example 2
Using JavaScript if/else Selection Statements.
Using window.confirm() dialog box.
Using window.close() function.
HTML File:
Filename: Control2.html
Example 3
Using JavaScript conditional/ternary operator.
HTML File:
Filename: Control3.html
Example 4
Using JavaScript switch statement.
HTML File:
Filename: Control4.html
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
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
HTML File:
Filename: Control6.html
Example 7
Using JavaScript for loops.
HTML File:
Filename: Control7.html
Example 8
Using JavaScript do/while loops.
HTML File:
Filename: Control8.html
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;
}
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:
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
Example 1
Function without arguments.
HTML File:
Filename: Function1.html
Example 2
Function with arguments.
HTML File:
Filename: Function2.html
Example 3
Function that returns a value.
HTML File:
Filename: Function3.html
Example 4
Function with arguments that return a value.
HTML File:
Filename: Function4.html
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
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
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.
HTML File:
Filename: Function7.html
8
Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or Less. Wiley Publishing, Inc., Indiana
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
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
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
Example 11
JavaScript Functions with HTML Forms
HTML File:
Filename: Function11.html
Math.round(9.45)
=9
Example 1
Using Math.random() method
HTML File:
Filename: Math1.html
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:
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
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
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
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
Example 4
Creating a Slide Show in JavaScript Automatically (with Blend Transition).
HTML File:
Filename: Array4.html
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
14
Reference: http://www.w3schools.com
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
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
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
Properties Description
Methods Description
15
Reference: http://www.w3schools.com
Example 1
Using length property and charAt(), concat(), indexOf(), lastIndexOf(),
match() and search() methods.
HTML File:
Filename: String1.html
Example 2
Using slice(),substr(),substring(),strike(),sub(), sup(),toLowerCase(),
toUpperCase(),toString() and valueOf() methods.
HTML File:
Filename: String2.html
Example 3
Scrolling Messages using subString() method
HTML File:
Filename: String3.html
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);
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.
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
16
Reference: http://www.w3schools.com , Reference: Danesh, A. (2004). JavaScript in 10 Simple Steps or
Less. Wiley Publishing, Inc., Indiana
Property Description
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
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
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
Example 3
Setting the Location & Controlling the Appearance of a New Browser
Windows.
HTML File:
Filename: Window3.html
Example 4
Opening a Full-Screen Window in Internet Explorer
HTML File:
Filename: Window4.html
Example 5
HTML File:
Filename: Window5.html
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.
<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
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
Example 2
Accessing Selection Lists. This example shows you how to check the current
selection in a selection list.
HTML File:
Filename: Form2.html
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
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
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
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
Example7
Detecting Check Box Selections. This example shows you how to check selection
status of a check box.
HTML File:
Filename: Form7.html
Example8
Changing Check Box Selections. This example shows you how to control selection
status of a check box.
HTML File:
Filename: Form8.html
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
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
Example11
Using Graphical Buttons in JavaScript. This example lets you place images
within a form as elements.
HTML File:
Filename: Form11html
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.
Example1
Creating a Simple Pull-Down Menu. This example outlines how to build an
extremely simple pull-down menu.
HTML File:
Filename: Dynamic1html
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
Example3
Sliding Menus.
HTML File:
Filename: Dynamic3.html