Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

LAB5 Javascript

The document discusses the fundamentals of JavaScript including what it is, what it can do, variables, functions, events, and manipulating page elements. It provides examples of JavaScript code and instructions for tasks like adding alerts, functions, and changing styles.

Uploaded by

umie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

LAB5 Javascript

The document discusses the fundamentals of JavaScript including what it is, what it can do, variables, functions, events, and manipulating page elements. It provides examples of JavaScript code and instructions for tasks like adding alerts, functions, and changing styles.

Uploaded by

umie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

LAB 5 /TSE2543

LAB MANUAL 5
Javascript
LEARNING OUTCOMES:
• Learn the fundamentals of implementing and distributing a JavaScript.
• Learn to use the JavaScript.
• Learn the fundamentals of implementing and distributing advanced
JavaScript.
• Learn to use the advanced JavaScript.

THEORY AND CONCEPTS:


WHAT IS JAVASCRIPT?
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is a scripting language
• A scripting language is a lightweight programming language
• A JavaScript consists of lines of executable computer code
• A JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute
without preliminary compilation)
• Everyone can use JavaScript without purchasing a license

WHAT CAN A JAVASCRIPT DO?


• JavaScript gives HTML designers a programming tool - HTML authors
are normally not programmers, but JavaScript is a scripting language
with a very simple syntax! Almost anyone can put small "snippets" of
code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript
statement like this: document.write("<h1>" + name + "</h1>") can write
a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a
user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

• JavaScript can be used to validate data - A JavaScript can be used to


validate form data before it is submitted to a server. This saves the
server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can
be used to detect the visitor's browser, and - depending on the browser
- load another page specifically designed for that browser
• JavaScript can be used to create cookies - A JavaScript can be used to
store and retrieve information on the visitor's computer.

VARIABLE

Think of a variable as a word that can contain a value. For example:

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:


1. Variable names are case sensitive
2. They must begin with a letter or the underscore character

IMPORTANT! JavaScript is case-sensitive! A variable named strname is


not the same as a variable named STRNAME!

FUNCTION

To keep JavaScript from mixing up same-name variables, put var in front


of your variables as you declare them. A variable inside a function that's
declared with var is called a local variable, and it only exists inside that
function. In general, you want your variables to be local whenever
possible.

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

Here is the JavaScript with the correct vars in it:

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

JavaScript
Please self-study XHTML and javascript in
http://www.w3schools.com

You’re assumed to know the basic of XHTML and javascript before


entering

1. First javascript code. Save as myJavascript.html

<html>
<head>
<META http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-5">
<title>First JavaScript example</title>
<script type = 'text/javascript'>
alert("This is an alert box!")
</script>
</head>
<body>
<H1>First JavaScript Example</H1>
<P>Theoretically, an alert box should
have popped up
before you see this text.</P>
</body>
</html>
The text in shaded background is new. The alert function pops up a dialog box.
You must click OK before you can see the page content.

JavaScript Errors

Let's create an error by removing the second quote mark in the alert
statement:
alert("This is an alert box!)

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

Save the file and use the Firefox File menu to open the saved version. You
should see the page content telling you about the alert box, but no alert
box popped up. The error caused the script to silently fail!
Since we are developers, we want to know why the script failed. From the
Firefox Tools menu choose Error Console. Click on Errors and you should
see the helpful message below.

Function and Event Handler

To control when an action takes place, we convert the action to a function.


Rewrite your file myJavascript.html as follows. The changed parts are
highlighted. Then save as myJavascript2.html.
<html>
<head>
<title> JavaScript Function
Example</title>
<script type = 'text/javascript'>
/*
* Pop up a meaningless alert, for
a demonstration.
*/
function show_alert() {
alert("This is an alert box!")
}
</script>
</head>
<body>
<H1>Second JavaScript Example</H1>
<P>You will not see the alert box this
time.</P>

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

</body>
</html>

Make the highlighted code changes to the BODY section of your


webpage and save the file as myJavascript3.html:

<H1>Event Handler Example</H1>


<P>To see the alert box, click the button
below.</P>
<div>
<input type='button' value='Click here'
onclick='show_alert()'>
</div>
When your run using web browser, you should see a button that pops up
the alert box when clicked.

You will see that this element has three attributes: its type (button),
value ('Click here') and the onclick event handler, show_alert.

One of our favorite JavaScript tricks is creating rollover effects. Make


the highlighted code changes to the BODY of the webpage and save the
file as myJavascript4.html:

<H1>Rollover Example</H1>
<P onmouseover='show_alert()'>Roll the mouse
over this paragraph to see the rollover
effect.</P>

In browser, navigate to myJavascript4.html. When you roll your mouse


over the paragraph, you should see the alert box.

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

Object references to page elements


OK, now we've demonstrated that we can respond to a mouse rollover
event. But what we'd really like to do is change the style of the element
that the mouse rolls over. For this we need a "handle" allowing us to write
code that actually changes a page element. This "handle" is called an
object reference to the page element. Here's how we get it:
Make the highlighted code changes to your webpage and save the file as
myJavascript5.html:
<title>W3C DOM tester</title>
<script type = 'text/javascript'>

function test_getElement() {
id = prompt("Please enter the id of a page
element");
obj = document.getElementById(id);
if(obj)
alert("Found element; its tag name is
"+obj.tagName);
else
alert("Sorry, I cannot find this element");
}
</script>
</head>
<body id='Suzie'>
<H1 id='Steve'>Object Reference Tester</H1>
<P id='Alice'>
Click the button to test the getElementById
function.</P>
<div id='Fred'>
<input type='button' value='Click here'
onclick="test_getElement()">

Again, there are lots of pitfalls with copying this code, so use the Error
Console to verify that you have it correct. Here are some of the new
features in the code:
• The prompt function is like alert, but it makes the user enter
some value that is returned to the script. The value the user types
in will be called id.
• We added id attributes to various tags in the document. These
are special markers to identify individual elements (just like your

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

student ID identifies you). You should not use the same id in two
different tags.
• The document.getElementById function tries to find the
page element that has a given id. If successful, the function
creates an object reference and stores it in the variable obj.
• The script needs to make one
of two different responses to
the user. If the user enters an
id that is found in the
document, the script will
reply with the tag name (P,
H1, etc.). But if the user
enters an id that is not found,
the script must give a 'not
found' message. To handle
this, the script uses an if-else
control statement. The flow chart for the script logic is shown to
the right.

Changing element styles


Remember that CSS style sheets are the preferred method for changing
style properties such as backgrounds, color, etc.

The best way to change element properties such as colors is to create a


named style (check the CSS section of the Reference Guide). You can
then use JavaScript to set the className property of the object to the
name of the style you want. Make the highlighted code changes and save
the file as JSExample6.html:

<title>Change element style</title>


<style>
.highlight {background-
color:blue;color:white;font-weight:bold}
</style>
<script type = 'text/javascript'>
function change_style() {
obj = document.getElementById('Alice');
obj.className='highlight';

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

}
</script>
</head>
<body id='Suzie'>
<H1 id='Steve'>Object Reference Tester</H1>
<P id='Alice'>
Click the button to alter the style of this
paragraph.</P>
<div id='Fred'>
<input type='button' value='Change to blue'
onclick="change_style()">

Using getElementById to locate an object reference to the


paragraph. This time, however, we don't need an if-else control
statement because we know that the element will be found.

When the script changes the className property of the element, the
display property will change! Be sure to capitalize the 'N' in className,
because JavaScript is a case-sensitive language.

Object Terminology
Note the special usage obj.className='highlight'.
Here obj is an object: a package containing a
bunch of data items that can be manipulated by a
program. One of the data items is className, the
name of the style used to display the paragraph
contents. By changing className, we have changed
the way the paragraph displays in the browser.

Function Parameter
We can make functions more flexible by providing parameters. These are
input values that give the function some details about how to do its job.
Make the highlighted code changes and save the file as
myJavascript7.html:

<script type = 'text/javascript'>


function change_style(theElement, theStyle)
{

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

obj =
document.getElementById(theElement);
obj.className=theStyle;
}
...
...
...
<input type='button' value='Change to blue'
onclick="change_style('Alice','highlight')">
Note that the function spec is now a bit more complex: this function can
change any element to any style you like, not just 'highlight'. Be careful
with the last line: it contains the single-quoted Alice and highlight inside
the double-quoted change_style().
This code should have exactly the same effect as myJavascript6.html. We
won't see the payoff from our latest improvements until we need to
change styles more than once.

Now you try it!


To make a true mouse rollover effect, we need a way to change the
paragraph style back to normal. Now it's time for you to write some code
on your own! Save your page as JSExample8.html, and edit it to add
another button. Here's what you will need to do:
• Define another named style in the STYLE section of your
webpage (check CSS Way in your Reference Guide for help). Call
the named style normal, which restores the default style of the
text paragraph (i.e. default styles to text is usually black colored
font on a white background-color. I leave it up to you to consult
http://www.blooberry.com/indexdot/css/index.html to figure out
the Allowed Value you want for the font-weight property).
• Add a new button that says "Change to normal." The onclick
attribute of the new button will be almost the same as the other
button. Can you figure out the difference?
With luck and persistence, you should be able to get this to work!

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

The final step: mouse rollover effect


Now you are ready to create a true mouse rollover effect. Save your file as
myJavascript9.html. Make the following two changes:
• In the paragraph tag, add an onmouseover attribute. This is the
mouseover event handler, so set its value to the onclick
attribute of the first button.
• In the paragraph tag, add an onmouseout attribute. This is the
mouseout event handler, so set its value to the onclick
attribute of the second button.
That's it! You should now have a true mouse rollover effect.

More text properties


In the code below, we create some buttons to manipulate various
properties of a text paragraph. Copy and paste all of this code into a new
Notepad2 document and save this as myJavascript11.html:
<html>
<head>
<title>Text Object Properties</title>
<style type="text/css">
.big {font-size:x-large}
.bold {font-weight:bold}
</style>
<script type='text/javascript'>
function change_size() {
paragraph_obj =
document.getElementById("para1");
paragraph_obj.className='big';
}

function change_weight() {
paragraph_obj =
document.getElementById("para1");
paragraph_obj. className='bold';
}
</script>
</head>
<body>
<H1>Text object properties</H1>

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

<P id='para1'>This is a typical text element.


Click on the buttons
below to change various properties of this
text.</P>
Can you add two buttons to this example, one to make paragraph text big,
the other to make it bold (you can look back at previous examples above
to remember how to make buttons)?
Can you add another button to change the paragraph background-color
to yellow? You may need to look in the Reference Guide.

Javascript and FORM


The purpose of this lab session is to use JavaScript within an XHTML page.
This exercise will set up the page so that a welcome message is posted
when the page is first loaded, then when the form submit button is
clicked, it will undertake some very basic form data existence validation.

1. Create a theatre booking form html page. (Like the one below)
2. Refer to the lecture notes and write the code that will show an alert
box with a welcome message when the page is loaded. (Hint: you
will need to set the onload event in the Body tag).

3. Test this within a browser to make sure it works.


4. Add the code to do the validation for the text boxes on the form. The
validation will be to make sure that the user enters in a value into the
text boxes. To do this first we need to add the function which will
do the validation as follows into the head section of the HTML page:

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

<script type="text/javascript"> This is the name of the


function checkall(frmEnquiry) form name text box
{
if (frmEnquiry.txtName.value == "")
{
alert("You must enter a name"); This is the onsubmit
return (false); attribute that will call the
} function checkall
}
</script>

Then add the code which will call this function to the form tag as follows:
<form method="post" onsubmit="return checkall(this);"
action="movie.html">

4. Test the code to make sure that the validation works like this:

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

5. Amend the code so that it also does the existence validation for both
the email and phone text boxes additionally.

6. Using the isNaN(frmEnquiry.txtPhone.value) function described


in the lecture add the validation to check additionally to see whether
the value entered into txtPhone is a number (hint you will need to
use || (this is the OR operator)).

7. Add the validation so that the email address contains an ‘@’


somewhere after the second character (look that the lecture notes
if you need help).

NOTE: JavaScript is case sensitive

8. Validate your work and create a word document to show the


validation results. You should also include the URL of your .html
page in the word document.

Test this javascript by your own!


1. Please type the below code and add three of your best friends’ names.

<html>
<head>
<title>My Bestie</title>

<script type = "text/javascript">


var testNumber = 109.4;
var name1, name2, name3;
var cream = false;
var sugar = true;

window.alert("testNumber = " + testNumber);


window.alert("name1 is " + name1 +
" ,name2 is " + name2 +
" ,name3 is " + name3);
window.alert("cream = " + cream +
" sugar = " + sugar);
</script>

</head>

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

<body>
<p> Click Refresh (or Reload) to run the script
again. </p>
</body>
</html>

2. Please type the below code and add three more questions and answers
based on chapter
<html>
<head>
<title>My Bestie</title>

<script type="text/javascript">

var firstAnswer;
var secondAnswer;

firstAnswer = window.prompt ("1. The Internet uses


a method of traffic " +
"control and flow
control known as");

window.alert ("You answered [" + firstAnswer + "]"


+
"\nThe correct answer is packet-
switching.");

secondAnswer = window.confirm ("True or false:


XHTML tags are case sensitive " +
"\(click OK for
true, Cancel for false\)");

window.alert ("You answered [" + secondAnswer +


"]" +
"\nThe correct answer is
\(true\).");

</script>
</head>

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM


LAB 5 /TSE2543

<body>
<p> Click Refresh (or Reload) to run the script
again.</p>
</body>
</html>

 END OF LAB SESSION 

KOLEJ POLY- TECH MARA BATU PAHAT UMI KALSUM

You might also like