Você está na página 1de 23

Introduction

Link imp:- http://ajax.net-


tutorials.com/controls/updatepanel-
control/

ASP.NET AJAX, previously called "Atlas", is a Microsoft implementation of an AJAX based


framework, created for ASP.NET (although it can be used on other platforms as well). AJAX
stands for Asynchronous JavaScript and XML, which, very simply put, is a way of
transferring data between the server and client without the sending the entire page, and
thereby creating a complete postback. This allows for a richer experience for the user, since
loading dynamic content can be done in the background, without refreshing and redrawing
the entire page. If you have ever used Gmail or Outlook Web Access, you have used an
Ajax enabled webapplication, and especially Google have made Ajax very popular.

While it's perfectly possible to use Ajax without Microsoft ASP.NET AJAX, a lot of things
are way easier, since Microsoft has wrapped some of most tedious parts of Ajax into their
implementation. For instance, the 3 most popular browsers requires different ways of using
Ajax, and have different JavaScript implementations. ASP.NET AJAX simplifies this a lot and
allows you to write the same code to target all 3 major browsers.

As usual, we will use the good old "Hello, world!" as our very first example. We will begin
with the code, and then we'll do a bit of explanation afterwards. If you haven't already done
so, you should create a new ASP.NET website project in Visual Web Developer. The IDE
will create a Default.aspx and Default.aspx.cs file for you, which will look just like any other
ASP.NET enabled page. Let's add some AJAX to it:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello, world!</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="pnlHelloWorld" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="lblHelloWorld" Text="Click the button!" />
<br /><br />
<asp:Button runat="server" ID="btnHelloWorld" OnClick="btnHelloWorld_Click"
Text="Update label!" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
In the CodeBehind, there's nothing new except for this event which you should add:
protected void btnHelloWorld_Click(object sender, EventArgs e)
{
lblHelloWorld.Text = "Hello, world - this is a fresh message from ASP.NET AJAX! The
time right now is: " + DateTime.Now.ToLongTimeString();
}
In the markup part, we use two new things, when compared to regular ASP.NET: The
ScriptManager control and the UpdatePanel control. The ScriptManager makes sure that the
required ASP.NET AJAX files are included and that AJAX support is added, and has to be
included on every page where you wish to use AJAX functionality. After the manager, we
have one of the most used controls when working with AJAX, the UpdatePanel. This control
allows you to wrap markup which you would like to allow to be partially updated, that is,
updated without causing a real postback to the server. More about the UpdatePanel in a
coming chapter. Besides those two controls, everything else is standard controls, with no
modifications that would indicate alternate behavior.

Try running the example site, and click the button. The label will be updated with our usual
Hello world text, and the current time. Try repeatedly clicking the button, and you will see
the label get the current timestamp each time. Notice the wonderful absence of a blinking
window and a running status bar - everything is done without updating anything but the
label! We've just created our first AJAX enabled page. If you wish to see how this page
would work without AJAX, try setting the "enablepartialrendering" of the ScriptManager to
false like this:
<asp:ScriptManager ID="MainScriptManager" runat="server" enablepartialrendering="false" />
This will disallow the use of partial rendering on the page, and show you how it would work
without AJAX.

In the following chapters we will look into the various AJAX controls and how to use them.

Having problems with this chapter? Ask in our forums!

UpdatePanel control
The UpdatePanel control is probably the most important control in the ASP.NET AJAX
package. It will AJAX'ify controls contained within it, allowing partial rendering of the area.
We already used it in the Hello world example, and in this chapter, we will go in depth with
more aspects of the control.

The <asp:UpdatePanel> tag has two childtags - the ContentTemplate and the Triggers
tags. The ContentTemplate tag is required, since it holds the content of the panel. The
content can be anything that you would normally put on your page, from literal text to web
controls. The Triggers tag allows you to define certain triggers which will make the panel
update it's content. The following example will show the use of both childtags.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdatePanel</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateButton2" eventname="Click" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel1" />
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click"
text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel2" />
<asp:Button runat="server" id="UpdateButton2" onclick="UpdateButton_Click"
text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Here is the CodeBehind. Just add the following method to the file:
protected void UpdateButton_Click(object sender, EventArgs e)
{
DateTimeLabel1.Text = DateTime.Now.ToString();
DateTimeLabel2.Text = DateTime.Now.ToString();
}
So, what's this example all about? Try running it, and click the two buttons. You will notice
that then first button updates only the first datestamp, while the second button updates
both. Why? We have set the Panels to update conditionally, which means that their content
is only updated if something insides them causes a postback, or if one of the defined
triggers are fired. As you can see, the first UpdatePanel carries a trigger which references
the second button. This will ensure that the first panel is updated even when a control on a
different UpdatePanel is used. The AsyncPostBackTrigger tag is pretty simple - it only takes
two attributes, the controlid, a reference to the control which can trigger it, and the
eventname, which tells which eventtype can cause the trigger to fire. If you wish for the
content of a UpdatePanel to be updated no matter what, you may change the updatemode
property to Always.

In general, you should only have UpdatePanels areound areas where you wish to do partial
updates. Don't wrap your entire page within an UpdatePanel, and don't be afraid to use
several panels, since this will give you more control of which areas update and when they
do it.

Having problems with this chapter? Ask in our forums!

UpdateProgress control
One of the problems with Ajax, is the fact that since it's asynchronus and in the
background, the browser will not show you any status. With fast servers and fast methods,
this is not a big problem, but whenever you have a method which takes up a bit of time,
the user is very likely to get impatient. Fortunately, ASP.NET AJAX solves this problem for
us as well, with a nice control called UpdateProgress. It will use your own template to show
that an asynchronus method is working. Have a look at the following example, which will
show the control in action. It will be explained afterwards.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdateProgress control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdateProgress runat="server" id="PageUpdateProgress">
<ProgressTemplate>
Loading...
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" id="Panel">
<ContentTemplate>
<asp:Button runat="server" id="UpdateButton" onclick="UpdateButton_Click"
text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
The following method should be added to your CodeBehind file:
protected void UpdateButton_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
This simple example will just show you how easy it is to use the UpdateProgress control.
Once the button is clicked, the script sleeps for 5 seconds (don't use code like that in your
real projects - it's for demonstrational purposes only!), and the "Loading..." text is displayed
on your page. You can use anything in the ProgressTemplate, including ordinary markup
and other controls. A common use is an animated GIF, positioned strategically on the page
using CSS positioning.

You can have multiple UpdateProgress controls on the page, and by using the
AssociatedUpdatePanelID property, you can make sure that the UpdateProgress is only
shown when a certain UpdatePanel is updated.

The DynamicLayout property is nice to know as well. It tells whether or not the page
should reserve space for your progress control. If it's set to true, which is the default, the
space is dynamic, hence it's not reserved, but taken when the control is shown. If you wish
to reserve the space, set this property to false. To see the difference, add the property to
our example and change it back and forth.

If some of your postbacks are fast, the UpdateProgress will only be shown for a very short
amount of time, resulting in a blinking behavior, which may confuse your users. For that
reason, you may specify a minimum amount of time to occur before showing the progress
control. This can be done with the DisplayAfter attribute. Specify a number of milliseconds
to elapse before showing the progress control, e.g. 2000 if you wish to wait for 2 seconds.

Timer control

Timer controls allow you to do postbacks at certain intervals. If used together with
UpdatePanels, which is the most common approach, it allows for timed partial updates of
your page, but it can be used for posting back the entire page as well. In this chapter we
will focus on using timers with UpdatePanels, so if you haven't already read the chapter on
UpdatePanels, please do so now.

Here is a small example of using the Timer control. It simply updates a timestamp every 5
seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timers</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000"
ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
We only have a single CodeBehind function, which you should add to your CodeBehind file:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This is all very simple. We have a normal UpdatePanel, which carries a Trigger reference
to our new Timer control. This means that the panel is updated when the Timer "ticks", that
is, fires the Tick event. The Timer control uses the interval attribute to define the number of
milliseconds to occur before firing the Tick event. As you can see from our CodeBehind
code listing, we just update the DateStampLabel each time the Timer fires. This could be
done more efficient with a simple piece of JavaScript, which updates the time on the
clientside instead of involving the server. The example is only used to demonstrate the
potential of the Timer control.

Another approach is including the Timer inside the UpdatePanel. Doing so would save us
from defining a trigger, but you should be aware of the fact that the behavior will be
different, depending on whether you have the Timer inside or outside an UpdatePanel.
When a Timer is inside an UpdatePanel, the Timer is not re-constructed until the
UpdatePanel is fully updated. That means that if you have a Timer with an interval of 60
seconds, and the update takes 5 seconds, the next event won't be fired 60 seconds after
the previous, but 65 seconds after. On the other hand, if the Timer is outside the
UpdatePanel, the user will only look at the content of the panel for 55 seconds before it's
updated again.

You should always remember that even though partial updates are not as heavy on the
server as real postbacks, the server is still contacted, and when using timers, you may get
a lot of partial postbacks, which can slow things down. Always use as high intervals as
possible, and consider if contacting the server is really necessary or not.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Home > JavaScript

JavaScript





 0diggsdigg

A scripting language developed by Netscape to enable Web authors to design interactive
sites. Although it shares many of the features and structures of the full Java language, it
was developed independently. Javascript can interact with HTML source code, enabling Web
authors to spice up their sites with dynamic content. JavaScript is endorsed by a number of
software companies and is an open language that anyone can use without purchasing a
license. It is supported by recent browsers from Netscape and Microsoft, though Internet
Explorer supports only a subset, which Microsoft calls Jscript.

888888888888888888888888888888888888888888888888888888888888888

What exactly is Javascript?:


Javascript is a programming language that is used to make web pages interactive. It runs
on your visitor's computer and so does not require constant downloads from your web site.
Are Javascript and Java the same?:
No, they are two completely different computer languages. Only their names are similar.
What do I need to run Javascript?:
Javascript support is built right into web browsers. Provided that the visitors to your site are
using web browsers that support Javascript (most do) and have Javascript enabled (it is by
default) then your Javascript will run.
Do I need to learn Javascript to be able to use it?:
No. There are plenty of Javascripts that have already been written that people have made
available for you to plug straight into your web page. All you need to know to be able to
use such scripts is how to paste the supplied code into the required places in your web
page.
What do I need to write Javascript?:
Javascript is an interpreted language and so no special program is required to be able to
create usable code. Any plain text editor such as Notepad is quite satisfactory for being
able to write Javascript. That said, an editor which colourizes the code to make it easier to
see what is what makes it easier to find your mistakes but then my Javascript Formatter
can reformat your script to make errors even easier to spot.
Can I use HTML instead of Javascript?:
No. HTML and Javascript are two completely different things. HTML is a markup language
designed for defining static web page content. Javascript is a programming language
designed for performing dynamic tasks.
Can I use PHP or some other server side language instead of Javascript?:
Perhaps, it depends on where the code needs to run. If it can run before the page loads
you can use a server side language. If it has to run after the page has loaded then you
must use Javascript as this is the only scripting language supported by all web browsers
that support client side scripting.
Does the Javascript go in the same file as the HTML?:
It can but your scripts will be more easily reused on multiple pages of your site if you
place them in separate files (using a .js extension helps identify them as Javascript). You
then just link the Javascript to your HTML by inserting a <script> tag. The same Javascript
can then be added to several pages just by adding the appropriate tag into each of the
pages to set up the link.

88888888888888888888888888888888888888888888888888888888

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

Are Java and JavaScript the same?

NO!

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming
language - in the same category as C and C++.

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

88888888888888888888888888888888888888888888888888888888888888888888888888888888
88888

Introduction

What's JavaScript? What's the difference between JavaScript and Java? Isn't JavaScript just
a simplified version of Java? These are common questions that I get all the time.

Netscape originally invented a simple scripting language called LiveScript, which was to be
a proprietary add-on to HTML. When Sun's new language Java became unexpectedly
popular, Netscape was quick to jump on the Java bandwagon, and re-christened their
scripting language JavaScript. Outside of the first four letters, there are almost no other
similarities between the two.

Microsoft then added their own version of JavaScript to Internet Explorer, which they named
JScript. Unfortunately, the two were not identical, so Netscape then attempted to straighten
matters out by turning JavaScript over to ECMA, a Switzerland-based standards body. This
gave three main versions of JavaScript-based languages: JavaScript, which works primarily
with Netscape's browsers, JScript, which works with Internet Explorer, and ECMAScript, with
which no browser is completely compatible. Netscape and Microsoft have both stated that
future versions will match the ECMAScript standard, which should lead to convergence.
However, as the most-used features are common to all, compatibility is not an issue unless
you are trying to use JavaScript to control DHTML.

JavaScript is growing in popularity due to its simple learning curve relative to the amount of
power it provides. Complete non-programmers are able to add a little bit of interactivity to
their web pages without buying an IDE or sweating over why a program won't compile.
There are numerous Web sites which contain any number of scripts available for the taking,
and Netscape has fairly complete documentation on their site. And of course, there's the
always useful ability to view the source of Web pages.
Syntax & Basics

The syntax of JavaScript will be simple to anyone who has ever programmed in an object
oriented language. The primary object is the window, which is at the top of the hierarchy.
Under that are the document, frame, location, history, and navigator objects. In turn, the
document object contains anchors, applets, embeds, forms, images, and links, each of
which is an array of objects. So, a reference to the first image on a page would be to
self.document.image[0], although it is preferable to use names instead of numbers for clarity.

JavaScript is not a stand-alone language, but rather a scripting add-on to HTML. JavaScript
is added to HTML commands by use of the <SCRIPT> tag. Anything within this tag is (or
should be) ignored by browsers that do not support JavaScript. JavaScript is the most
popular scripting language in use due to its cross-platform and cross-browser support,
although VBScript is sometimes used on intranets when the scripter knows that everyone
accessing the page is on Windows. JavaScript will attempt to execute the commands within
the <SCRIPT> tag if there is no LANGUAGE attribute, or if the LANGUAGE attribute is set
to JavaScript; in addition, the LANGUAGE attribute also can be used to distinguish between
various versions of JavaScript.

The JavaScript in Listing 1 consists of a single line: document.write("Hello, World!"). This


writes the typical "Hello, World" message, using the document.write() method. This method
dynamically generates text within HTML files, in lieu of hard-coded HTML. Figure 1 shows
the results.

Listing 1: Everyone's first script

hello.html

<HTML>
<HEAD>
<TITLE>Barely a script at all</TITLE>
</HEAD>
<BODY BGCOLOR=WHITE>
<H1>
<SCRIPT LANGUAGE="JAVASCRIPT">
document.write("Hello, World!")
</SCRIPT>
</H1>
</BODY>
</HTML>
Figure 1. The typical "Hello, World".

Using JavaScript

There are three ways that JavaScript can be used within an HTML file. It can be put within
<SCRIPT> tags within the <HEAD> tag (header scripts), within <SCRIPT> tags within the
<BODY> tag (body scripts), or called directly when certain events occur.

JavaScript is put inside the <HEAD> tag primarily when you are initializing variables and
creating functions that will be used throughout the entire script. Code here is executed
once, when the page is loaded. Within the <BODY> tag, the best use of JavaScript is to
write out text on-the-fly. JavaScript handles these events:

Event Caused by

onAbort The user aborted loading the page

onBlur The user left the object

onChange The user changed the object

onClick The user clicked on an object

onError The script encountered an error

onFocus The user made an object active

onLoad The object finished loading

onMouseOver The cursor moved over an object

onMouseOut The cursor moved off of an object

onSelect The user selected the contents of an object


onSubmit The user submitted a form

onUnload The user left the window

Any of these event handlers can be added to any HTML tag which can cause the event to
occur. For example, the onLoad event handler can be added to the <BODY> tag, and the
event will be called when the page has completed loading.

Image Rollovers

One of the most common uses of JavaScript is the image rollover. This is a technique
which requires little programming knowledge, but can greatly enhance the experience of
visiting a Web site.

HTML has its place, but it's static. A user entering a web site and seeing a window like
that in Figure 2 doesn't know what they should do -- are these words links, or just graphics
giving us information?

Figure 2. The Navigation Bar, upon entering the page.

Adding a rollover to this gives the look in Figure 3. Now, when a user moves a cursor
over any of the options, it becomes clear that this is a navigation bar, and that each of
these words is a live link.
Figure 3. When doing a rollover, the arrow gives the user feedback.

Image rollovers are handled by browsers that support JavaScript versions 1.1 and later,
which includes Netscape Navigator versions 3 and above, Internet Explorer 4, and some
versions of Internet Explorer 3. Listing 2 shows the code to create the image rollover effect.

Listing 2: Image rollovers give users feedback

navbar.html

<HTML>
<HEAD>
<TITLE>Navbar</TITLE>

<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- Hide from old browsers

if (document.images) {
productOn = new Image
pricingOn = new Image
pressOn = new Image

productOff = new Image


pricingOff = new Image
pressOff = new Image

productOn.src = "products_on.gif"
pricingOn.src = "pricing_on.gif"
pressOn.src = "press_on.gif"
productOff.src = "products_off.gif"
pricingOff.src = "pricing_off.gif"
pressOff.src = "press_off.gif"
}
else {
productOn.src = ""
pricingOn.src = ""
pressOn.src = ""

productOff.src = ""
pricingOff.src = ""
pressOff.src = ""

document.products = ""
document.pricing = ""
document.press = ""
}

// Stop hiding from old browsers -->


</SCRIPT>
</HEAD>

<BODY BGCOLOR=WHITE>
<A HREF="products.html"
onMouseOver="products.src=productOn.src"
onMouseOut="products.src=productOff.src">
<IMG src="products_off.gif" WIDTH="226" HEIGHT="37"
BORDER="0" NAME="products"></A><BR>

<A HREF="pricing.html"
onMouseOver="pricing.src=pricingOn.src"
onMouseOut="pricing.src=pricingOff.src">
<IMG src="pricing_off.gif" WIDTH="189" HEIGHT="80"
BORDER="0" NAME="pricing"></A><BR>

<A HREF="press.html"
onMouseOver="press.src=pressOn.src"
onMouseOut="press.src=pressOff.src">
<IMG src="press_off.gif" WIDTH="154" HEIGHT="36"
BORDER="0" NAME="press"></A>
</BODY>
</HTML>

In the <HEAD> tag, we do our initializations. The first thing needed is to hide the
JavaScript commands from browsers that are too old to understand JavaScript and too old
to understand that they're supposed to ignore text within tags they can't handle. This is
done by starting a HTML comment, which is not closed until just before the closing script
tag. This closing comment line works because it starts with a JavaScript comment symbol,
which causes JavaScript to ignore it. Next, we check to see if the browser we're using
supports manipulation of image objects. If it doesn't, then care must be taken to avoid
giving the user errors. This is done by checking for the existence of document.images. If it
exists, we're able to do the rollover. If it doesn't, they have an old browser (JavaScript 1.0)
or they have JavaScript turned off.

The image rollover technique requires two versions of each image: one "on" and one "off,"
based on whether the cursor is or isn't on top of the image. So, for each of the three
images in the window, we need to create 2 new image objects. We then assign an image
URL to each of these image objects, by setting their src property. This both enables the
variables to be referenced by name later within the body, and pre-loads the graphics into
the browser cache, so that they appear virtually immediately when the cursor moves over
the image.

We also give each image on the page a name, by setting the NAME attribute of each
within the <IMG> tag. While images can be referred to as document.image[0] (for instance),
it is more flexible & manageable to instead refer to document.products. This allows us to
refer to the image by name later when we want to manipulate it.

If the user has a browser that does not support image manipulation, we must initialize the
same variables, so that using them later does not cause an error. Consequently, we set the
src of each to the empty string. In addition, we set three other variables:
document.products, document.pricing, and document.press. Older browsers don't understand
that images can have names, so simply defining them here lets us use the objects in all
browsers without an error.

Within the body, we add event handlers to the link tags around the images, for both
onMouseOver and onMouseOut. For example, when the products image first loads, it
displays the image products_off.gif. When the cursor goes over the image, the src of
products is reset to the src of the productOn image that we set in the header script. This
displays the version of the image with an arrow. When the cursor is moved off the image
area, the src of products is reset to the src of the productOff image (set in the header
script).
If the browser does not support image manipulation, the onMouseOver event instead just
sets the src of an empty string to the src of another empty string, with no errors and no
effect.

The secret to having this look good is proper preparation of the images, avoiding the two
most common mistakes. Firstly, the two images must be of identical sizes. When one
replaces the other, the size of the image area doesn't change, even though the images
themselves may be of different sizes. Instead, the browser will automatically resize the
graphics for you, with unpredictable (and virtually always unpleasant) results. Figure 4
shows the six images actually used in this example. The "off" versions of the images,
although they do not include the red arrow, have identical dimensions to their "on" versions.
Secondly, the images must not have transparent areas. In this case, if the white areas were
transparent, the images would look fine upon first loading, and would also look fine when
the cursor was moved over them. But, when the cursor was moved off the first time, the
red arrow would continue to show through the transparent area of the "off" image.

Figure 4. There are actually 6 images; 1 each with and without the arrow.
JavaScript Navigation

Another way of improving the user interface of a web site is to improve its navigation. One
technique of doing this is to create a jumping popup menu, such as the ones on Apple's
DevWorld site. This example requires little actual scripting, outside of handling the
onChange event from the popup menu, combined with some knowledge of how JavaScript
interacts with HTML.

The HTML <SELECT> is used to create the popup menu shown in Figure 5. It has four
options: "Pick an area," "Products," "Pricing," and "Press." Choosing an option triggers the
onChange event, which evaluates the line of JavaScript shown in Listing 3.

Figure 5. This popup menu sends you to a new page instantly.

Listing 3: Instant navigation with a popup menu

popup.html

<HTML>
<HEAD>
<TITLE>Pop-up Menu</TITLE>
</HEAD>
<BODY BGCOLOR=WHITE>
<P>Where do you want to go?</P>
<FORM>
<SELECT
onChange="if (this.selectedIndex > 0)
window.location.href=this.options[this.selectedIndex].value">
<OPTION>Pick an area
<OPTION VALUE="products.html">Products
<OPTION VALUE="pricing.html">Pricing
<OPTION VALUE="press.html">Press
</SELECT>
</FORM>
</BODY>
</HTML>

Firstly, we check the value of selectedIndex. This is a number between 0 and 3, depending
on which option was chosen. If the option chosen was the first ("Pick an area"), we don't
want to do anything, so we only do anything if this.selectedIndex is greater than zero.

Otherwise, changing the value of window.location.href will force the browser to load a new
page. This example uses the HTML VALUE attribute of <OPTION> to store the new page
that we want to jump to. Each of these values can be referenced by JavaScript via the
value property of the options array. When the user chooses an option, JavaScript finds the
new page by referencing into the options array with the selectedIndex, and using its value
as the location of the page.

One of the major benefits of this style of handling popup menus is that changes to the
menu can be made with no knowledge of JavaScript necessary. In fact, once the onChange
handler has been added, the page can then be modified by WYSIWYG editors with no loss
in functionality, so long as the VALUE attributes are maintained correctly.

There's one small trick here: if you decide to change the popup so that the first option on
the menu is a valid location, the user won't be able to ever get there. The event handled is
onChange, and there's no way for a user to cause it to be triggered when choosing the
default option.

Flow Control

Like most programming languages, JavaScript has the expected ways of controlling the flow
of commands. Listing 4 and Figure 6 demonstrate functions, loops, and if statements in
JavaScript.

Listing 4: Controlling flow in JavaScript

factorial.html

<HTML>
<HEAD>
<TITLE>Factorial</TITLE>

<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- Hide script from old browsers

function showFactorial(theEntry) {
document.myForm.result.value =
calcFactorial(theEntry.value)
}

function calcFactorial(inVal) {
if (isNaN(inVal)) // isNan = Is Not a Number
return("Not a number")

startVal = eval(inVal) // eval turns a string into a number


if (startVal < 0 || startVal != Math.floor(startVal))
return ("Invalid number")

endVal = 1
for (i=1; i<=startVal; i++) {
endVal = endVal * i
}
return(endVal)
}

// End hiding script from old browsers -->


</SCRIPT>

</HEAD>
<BODY BGCOLOR=WHITE>

<H3>The factorial of
<FORM NAME="myForm">
<INPUT TYPE=TEXT SIZE=3
onChange="javascript:showFactorial(this)"> is
<INPUT TYPE=TEXT NAME="result">
</FORM>
</H3>
</BODY>
</HTML>

In this example, the user enters a number in the first field. Changing this field passes
control to the onChange event handler, which calls the showFactorial() function, with the
entry field as its parameter. The showFactorial() function calls the calcFactorial() function,
passing it the value of the entry field.

The calcFactorial() function returns either an error message (if not a number, less than
zero, or not an integer) or the factorial to its caller. When control passes back to
showFactorial(), the result is put into the result field in the browser window.

Figure 6. Entering a number displays its factorial.

Conclusion

Another popular use of JavaScript is form validation, which will tell the user if the form
they've submitted is valid without having the overhead of connecting to a Web server. This
technique gives the user the impression of speedy Web access, when they haven't
accessed your server at all.

JavaScript is growing in popularity, due to many factors, including its ease of learning, the
growing share of JavaScript-enabled browsers, and the large number of resources available
to novices. With Dynamic HTML on the horizon, JavaScript will become more important and
more prevalent in the future.

Bibliography & Suggested Reading

 Castro, Elizabeth. HTML for the World Wide Web., Visual QuickStart Guide. 2nd edn.
Peachpit Press, 1997.
 Flanagan, David. JavaScript: The Definitive Guide. 2nd edn. O'Reilly & Associates, 1997.
 Negrino, Tom and Dori Smith. JavaScript for the World Wide Web, Visual QuickStart Guide,.
2nd edn. Peachpit Press, 1998.

Você também pode gostar