 BACK |
Part 4 - Events (Making it happen!)
|
|
Introduction
We now have a basic grasp of the objects that make up JavaScript. We
need two things before we can consistently write functional code. These
two things are:
- A deep understanding of events;
- Knowledge of how frames work.
The first we will learn now, the latter on the next page of our tutorial.
What is an event?
Remember page two, where we showed how to
conveniently hijack a harmless reset button with the code:
onClick='GoThere(myform.yourName)'
You already know what an event is! What the above code does is to
respond to an event - when the unsuspecting user clicks on the
button, the function GoThere is used as an event handler.
JavaScript recognises the event, and knows that she must invoke GoThere to do her
dirty work. Such processing of events is an integral part of JavaScript,
and really gives it its power!
Many, perhaps most JavaScript objects have associated events that
can be identified and similarly 'hijacked'. There are events associated
with links, images, forms, windows and even fancy things like image maps.
Most JavaScript tutorials provide you with long lists of all the possible
objects that can be associated with events, and then even longer lists
of events for each object. We've chosen to do things the other way
around, and concentrate on the events.
A quick 'hijacking' of version 1.0
This is generally pretty easy. Inside the tag that you wish to hijack,
you insert code that looks like the following:
onEvent="DoSomething()"
Clearly the Event must
be one of the possible events for that object, and DoSomething is pretty
well what we want it to be - we all know how to define a function!
If you're having trouble with a particular event, it's easy to
debug it - put in an alert("This is a debug statement") type
of entry, and then check out the event.
We are also already familiar with the most important trip-wire
stretched in front of us to impede our progress - those darned double
quotes which we dare not use inside another set of double quotes - You
cannot say this sort of thing:
onClick="alert("This is the wrong thing to do")"
as it will die horribly. We also know the solution - either use
single quotes within the double ones, or escape the inner double
quotes with a backslash.
Without further ado, here are the events you can intercept and use:
And that's about that! (The onSelect seems to work inconsistently in
Netscape).
You'll find that you use the mouse events
quite a lot, and the form event onChange fairly frequently too.
Depending on what you're doing, you might also make good use of the
onBlur and onFocus events too, or even some of the others.
All in all, the list is not nearly as intimidating as one would expect!
Here are a few thoughts..
- Remember when we explored window.status
in part 3 of our tutorial? We said the
following:
<A HREF="err.htm" onClick="status='You clicked me';return false">
meticulously returning a false value. Such obsession
with falsehood is justified for all events. If you don't return true, the
action associated with the click event is cancelled. You can see that you
can prevent a click on a link from ever succeeding by simply
inserting the following code into an anchor:
onClick="return false"
(You can then use the anchor for other purposes!)
An even more devious amendment is the following:
<A HREF="javascript:void(0)" onMouseOver="status='Go to Hell';">
What does this do? It tells the browser that it must invoke
javascript (one can do this sort of thing in an HREF), and the
void(0) then says 'do nothing'! This sort of trickery prevents
the link from ever being followed. aVoid it! The void() function
is not guaranteed to exist in all JavaScript-enabled browsers. If
you must use this sort of trickery then:
- First define a function called, say, aVoid() that does nothing!
- Don't put the javascript: instruction inside the href.
Rather say something like:
<A HREF="err.htm" onClick="this.href='aVoid()';status='Go to Hell';">
- You can even have an error page (err.htm) that says "Woops. JavaScript error"
as a backup!
Another option to prevent the HREF from going anywhere is to point
the HREF to the current position (make an anchor) on the current page!
-
You may have noticed that, had you asked your browser to reload
the previous page (part three of the tutorial), instead of the status
bar displaying the friendly message:
"Welcome to part THREE of our tutorial!"
it might just have said "Done". This is the sort of thing you
don't want - your browser wrote the message, and then overwrote it with
its own bland pronouncement! We now have a way of detecting when the body of
a document has finished loading - onLoad. Reload the current page, and
see the message still lurking on the status bar.
- Client-side image maps are fairly cute. (Remember that
they will totally incapacitate a user whose browser isn't JavaScript
enabled). The idea is that you set up an image, and respond to the
coordinates of the user's click on the image. Some trickery is required.
The tricks are:
- Create a <MAP>
- refer your image to the MAP
- define the clickable areas within the MAP, and the responses
you want
This is not as intimidating as it sounds. Here's a rough idea
of how we do it:
Creating a client-side image map
|
<MAP name="jim">
<AREA coords="10,15,60,90" href="gohere.htm"
onMouseOver="alert('Argh')">
<!-- YOU CAN HAVE MORE AREAS HERE-->
</MAP>
<img src="clicpic.gif" width="100" height="120"
alt="whatever"
USEMAP="#jim">
|
- Emulation can be exciting (in v 1.2 and above)! You'll find that generally
where an event can be responded to, the object has an associated
method that accurately EMULATES this event. For example,
you can click on a button called, say, jane, but the button
will also have a method jane.click() that, when invoked,
will cause jane to "appear to be clicked by you"! Can you think of
a use for this?
Intercepting events in JavaScript 1.2
Note well (VERY well) that the following event handler stuff only
applies to Netscape JavaScript version 1.2 and above.
We're only having a brief peek now - we'll cover advanced event handling
more fully in part seven of our tutorial.
Another way of saying which function is going to respond to which
event is:
object.event = functionName
For example, let's say we want to trap all onClick events
for a document,
passing the event to our handler function Yeehah(). We could say:
document.onClick = Yeehah
NOTE that we do NOT have parentheses
after the function name. THIS IS IMPORTANT. It also only works in
JavaScript 1.2 and above.
How do we then construct our "event-handling" function? Well,
just as we would any other function, but we must remember that
the function is passed an argument. Let's create a click event
handler thus:
A onClick event handler
(Netscape JavaScript 1.2 and above)
|
function Yeehah(ev)
{ var butn = ( (ev.which == 1) ? "left" : "right" ) ;
alert ("You clicked at screen coordinates ("
+ ev.screenX + ","
+ ev.screenY + ") using the "
+ butn + " mouse button!"
);
}
document.onClick=Yeehah ;
|
If your browser supports version 1.2, you've already been warned,
and irritated, by just such a capturing of mouse clicks.
Note that the event handler is rather unreliable - if you click with
the right button in many browsers, the event will NOT be trapped.
If you view the source, you'll see that we cheated
a bit - and wrote in code that should be supported by both Netscape and
Internet Explorer! The code is also a bit more robust than the example,
which in fact works rather poorly in Netscape.
By the way, see how we said:
(ev.which == 1) ? "left" : "right"
This is a quick and nasty way of selecting between two choices: if
the test within parenthesis succeeds, then the first option is chosen;
if the test fails, the second value is returned. (We don't particularly
like this, but as it's often used, thought you should learn it at
some stage)!
|
We said that the above is for Netscape - what about MSIE? Well, there
are several differences. The most important one is that in MSIE, there
is no event passed to the function (ev in the above code) -
one can however interrogate a very similar object called window.event
that strangely and suddenly pops into existence when one handles an event using
an event-handling function.
As an example, the above is pretty useless. There is however a whole
variety of events that you can now (more or less) trap in JavaScript
1.2 - we won't discuss them here, but will defer this to part seven
of our tutorial.
Most JavaScript tutorials delve heavily into events and page structure.
Few give a concise view of what parts of a page can be changed, and
what is sadly immutable!
(We will eventually get around to providing a detailed reference
of which components can be altered in which browsers. For now, you'll
just have to find this out for yourself).
Now that you understand much more about events, we've provided a brief
diversion, where we look at
designing and implementing a form, all
souped up with JavaScript. If you wish to skip this, then you can
rush on and find out about frames.
|