Navigator 4.0 supports a new version of JavaScript (version 1.2). This version has many new features, especially in the area of event handling. New event handlers have been added to those supported in earlier versions of JavaScript. Moreover, there is an event object. With this object, it is possible to capture and handle events before they reach their default target.
What are events? Events occur as the result of an user
action. For example, clicking a button is an event, as is changing a text
field or moving the mouse over a hyperlink. You can define event handlers,
such as onChange and onClick, to make your script react to events. This
TechNote, we will include examples of how to use the new JavaScript 1.2
events in your web pages.
Event
Capturing
onDblClick
onDragDrop
onKeyDown
onKeyPress
onKeyUp
onMouseDown, onMouseMove and
onMouseUp
onMove
onResize
Conclusion
Resources
Before we consider the new event handlers, let's briefly discuss event capturing. Many of the examples in this TechNote use this new feature.
With JavaScript 1.2, you can now have a window or document capture and handle an event before the event reaches its default target. To accomplish this, the window, document, and layer objects have the following new methods:
To capture an event (for example, onMouseUp in a window), we use this syntax:
window.captureEvents(Event.MOUSEUP) //Note MOUSEUP is uppercased
The argument to captureEvents is a property of the event object and indicates the type of event to capture. To capture multiple events we would use a separator ( | ) like this:
window.captureEvents(Event.MOUSEUP | Event.CLICK | Event.MOUSEDOWN);
Now we create a function to be invoked as the event handler:
function clickHandler(myEvent)
{
/*
function statement
goes here..
Here you can do any
of the following:
1. return false
2. return true
3. Call routeEvent()
method
4. Call handleEvent()
method
*/
}
In the function, note that we pass a parameter called myEvent. This parameter is the event object for the event.
To make this function the handler for the onClick event, we use this syntax:
window.onClick = clickHandler;
To learn more about event capturing and the event object, check the
JavaScript
1.2 documentation.
The onDblClick event handler will invoke JavaScript code if you double click on a document, area or link object. The following code shows how to invoke an alert when someone double clicks on a button.
<form>
<INPUT Type="button"
Value="Double Click Me!"
onDblClick="alert('You just double clicked me!')">
</form>
Here inside the <INPUT> tag, we difine a button. We use the onDblClick event handler which points to an alert() method of the window object.
The onDragDrop event handler is invoked JavaScript code when you drag an object (for example, a file) onto the navigator window. Here is an example:
<BODY BGCOLOR="#FFFFFF" onDragDrop="alert('Did you just drag something?')">
In the <BODY> tag, the onDragDrop event handler is an alert() method. When the visitor tries to do a drag and drop (for example, dropping a file on the window), an alert will display "Did you just drag something?".
This event handler is invoked JavaScript code when the user depresses a key on a document, link or a Textarea object. Here is an example of using onKeyDown event for filtering input. In our example we make sure that the user cannot input "a" or "A" in the text box. Here is the code:
<form name="main">
<input name="textentry"
type=text size=10 maxlength=10>
</form>
function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
return false;
}
document.main.textentry.onkeydown = blockA;
First we create the textbox and name it textentry. Next we create a function which will be the onkeydown event handler for the text box. In the function, we have a variable called keyChar. This variable holds the key that was pressed by the user. Note that we are using the which property of the event object, and we pass that argument to the fromCharCode() method of the string object. Next we use an if statement which executes a "return false" if keyChar holds either A or a. This means that when the user inputs "a" or "A", the textbox will not show the value.
The onKeyPress event handler is invoked when the user presses or holds down a key. In this example, we will first capture the event and then show how to use the JavaScript scrollBy() method in conjunction with the user input. If you keep pressing "A" or "a", the page will scroll down and if you keep pressing "Z" or "z" the page will scroll up. Here is the code:
function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
self.scrollBy(10,10);
else if(keyChar == 'Z' || keyChar == 'z')
self.scrollBy(-10,-10);
else return false;
}
document.captureEvents(Event.KEYPRESS);
document.onkeypress
= blockA;
First we use the captureEvents()
method to capture the KEYPRESS property of the event object. Then we set
the onkeypress
property of the document object to the blockA
function. As in the onKeyDown event example, in this function we first
assign the variable keyChar
to the key that was pressed. If the variable
holds "A" or "a", we pass the x and y (positive value to scroll down)
increments to the scrollBy()
method. If keyChar
holds a "Z" or "z", we pass negative x and y increments to scroll up.
The onKeyUp event handler is invoked
JavaScript code when the user releases a key on a document, Image,
Link or a Textarea object. In this example, we see how to
capture this event in a document and call a function when the user releases
any key. Here is the code:
function Key_Up(e) {
var keyChar = String.fromCharCode(e.which);
alert("Hold '" + keyChar +"' again for me, okay?");
}
document.captureEvents(Event.KEYUP);
document.onkeyup=Key_Up;
As before, we capture the event by using the captureEvents() method and call the function Key_up() by assigning the onkeyup property of the document object. This function uses the fromCharCode() method and the which property of the event object to find out which key was pressed. Later an alert() method alerts the users asking to hold that key again once the key is released.
To demonstrate the new mouse events we have created an example that uses all of them. Let's begin with an overview of what these events do.
The onMouseDown event handler is invoked when the user depresses a mouse button on a Button, document or a Link object.
The onMouseMove event handler is invoked when the user moves the cursor.
The onMouseUp event handler is invoked when the user releases a mouse button on a Button, document or a Link object.
Now let's use these event handlers to create an example in which you can drag an image and place it anywhere on the page. Here is how we set up the image using Netscape Communicator's support for Positioning HTML Elements with Cascading Style Sheets (CSSP):
<HEAD>
<STYLE type="text/css">
#container1
{ position:absolute; left:200; top:200}
</STYLE>
</HEAD>
<BODY>
<P ID="container1">
<img src="backgrnd.gif"
name="myImage" width=96 height=96>
<script>
......
</script>
</P>
</BODY>
First we set the ID attribute for the P element to container1. This makes container1 the unique identifier for this element. No other element in this file is allowed to have the same ID attribute value, so we can use this unique identifier to refer to the element from within style sheets and JavaScript code.
Using CSSP syntax, we position the P element on the page, defining its position on the screen using the top and left attributes. Whenever an HTML element is positioned explicitly by a style sheet or by JavaScript code, a new Positioned HTML Element Object (or layer object for short) is created in memory. We can then move the HTML element on the page by accessing and setting the properties of this Positioned HTML Element Object.
Now lets examine the contents inside the <SCRIPT> tags. First we capture the MOUSEUP and MOUSEDOWN events for the object:
container1.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN);
Next, we make DRAG_begindrag the handler for the the onmousedown event and DRAG_enddrag the handler for the onmouseup event:
container1.onmousedown=DRAG_begindrag;
container1.onmouseup=DRAG_enddrag;
Let's see the code for the DRAG_begindrag() function:
function DRAG_begindrag(e)
{
if (e.which == 1) {
window.captureEvents(Event.MOUSEMOVE);
window.onmousemove=DRAG_drag;
DRAG_lastX=e.pageX;
DRAG_lastY=e.pageY;
DRAG_dragging=true;
return false;
}
else {
/*Do any right mouse button processing here*/
return true;
}
}
In this function, we first check whether the left mouse button is pressed. If so, we capture the MOUSEMOVE event. This causes all subsequent MOUSEMOVE events to be intercepted; they will be handled by function DRAG_drag, below.
Next we assign the value of the event's pageX property to DRAG_lastX, the value of the event's pageY property to DRAG_lastY, and true to DRAG_dragging. These are the global variables for this example. Finally the function returns false so that we end the event handling for this event.
Note that the function returns true when the user clicks on the right mouse button. We return true because when the user clicks on the right button, we want the event to be handled by Communicator's default behavior (in this case, displaying a popup menu).
Our next function, DRAG_drag(), is called when the user drags the object. It is invoked as the handler for the onMouseMove event:
function DRAG_drag(e)
{
if (DRAG_dragging) {
/*This function is only be called when MOUSEMOVEs are being captured*/
moveBy(e.pageX-DRAG_lastX, e.pageY-DRAG_lastY);
DRAG_lastX = e.pageX;
DRAG_lastY = e.pageY;
return false;
}
else {
return true;
}
}
The function first checks to see if the MOUSEMOVE event was captured previously by any other function. If so, we use the moveBy method to place the object in the location where the user stopped dragging. We also set the new values for DRAG_lastX and DRAG_lastY and finally return false. The function will return true if the MOUSEMOVE event was not captured previously by the DRAG_begindrag() function.
The last function DRAG_enddrag() is invoked when the user lets the mouse button go. In this function, we release the MOUSEMOVE event. We are using the releaseEvents() method here. We also have to make sure that when this function is invoked on other function is called after words. So we assign a null to the onmousemove event. Finally we set the variable DRAG_dragging to false. Note again that we check to see if the right or left mouse button was released. Here is the code:
function DRAG_enddrag(e)
{
if (e.which == 1) {
window.releaseEvents(Event.MOUSEMOVE);
window.onmousemove=null
DRAG_dragging=false;
return false;
}
else {
/*Do any right mouse button processing here*/
return true;
}
}
The onMove event handler is invoked when the user or script moves a window or a frame. To demonstrate how this event handler works, we create a button that opens a new window. When the user tries to move this floating window across the screen, he or she is alerted with a message. Let's take a look at the code that opens the new window:
<form>
<input type="button"
value="Click Here First" onClick="open_now()";>
</form>
Here we have a button that calls the function open_now() when the user clicks on it. Note that we are using the onClick event handler to invoke the function. Function open_now() looks like this:
function open_now(){
var
myWindow;
myWindow=window.open("","displayWindow","width=400,height=400,menubar=no,
location=no,alwaysRaised=yes");
var
text="<html><head><title>Test</title></head>"
+"<body bgcolor=white><h1>Please move this window</h1></body>"
+"</html>";
myWindow.document.write(text);
myWindow.captureEvents(Event.MOVE);
myWindow.onmove=fun2;
}
Here we have a variable called myWindow whose contents are the new window displayWindow. We use the open() method and set the width, height and other properties of the window. Next we have another variable called text which holds some HTML tags. We use the write() method to write these HTML tags into the new window dynamically. Next we capture the MOVE method and finally call another function called fun2(). This function does nothing but alert the user when the window is moved. To make sure that the window has focus after the user clicks on the OK button of the alert box, we use the focus() method. Here is the code for fun2():
function fun2(){
alert("Hey
you moved me!");
this.focus();
//'this' points to the current object
}
The onResize event handler is invoked when a user or script resizes a window or frame. To demonstrate how this event handler works, we will use the same code from the onMove event handler example. In this example, when the user tries to resize a newly opened window, he or she is alerted.
You will notice that the code is similar to the onMove event handler example:
function open_now(){
var
myWindow;
myWindow=window.open("","displayWindow","width=400,height=300,resizable=yes,
menubar=no,location=no,alwaysRaised=yes");
var
text="<html><head><title>Test</title></head>"
+"<body bgcolor=white><h1>Please resize this window</h1></body>"
+"</html>";
myWindow.document.write(text);
myWindow.captureEvents(Event.RESIZE);
myWindow.onresize=alert_me;
}
Let's focus on the code that differs from the onMove example. In the open_win() function, we have the following lines that are different:
myWindow.captureEvents(Event.RESIZE);
myWindow.onresize=alert_me;
Those two lines of code capture the RESIZE event and cause it to invoke the handler function alert_me():
function alert_me(){
alert("Hey
you resized me! \nNow my outer width: " + this.outerWidth +
"\n and my outer height: " +this.outerHeight);
this.focus();
}
As in the fun2() function of the onMove event handler example, we use an alert() method to first alert the user that the window was resized. Then we display the outer height and width of the window using the outerWidth and outerHeight property of the window. As before, to focus the window after the user click son the OK button of the alert box, we use the window's focus() method.
Using these basic techniques and the JavaScript 1.2 event handlers, you can develop more creative and practical applications such as advanced input filtering and validation. These event handlers are essential to Netscape Dynamic HTML programming. With Dynamic HTML and these new events, you can now create CD-ROM-like presentations and animation. To learn more about how to use Dynamic HTML, please check out the documentation on Dynamic HTML. You can also download the example files from this TechNote by following this link.
Documentation
JavaScript
1.2
JavaScript
1.1
Web Sites
JavaScript Resources A
2 Z
Communicator
Demos
TN-JSCR-04-9707