sivaramaiah  
 
  JavaScript4 04/20/2024 12:13am (UTC)
   
 

New events

Time to have a look at one of the new features of the Netscape Navigator 4.x: the event model

of JavaScript 1.2. The examples shown here will only work in Netscape Navigator 4.x (most

examples will also work in preview releases).

The following events are supported in JavaScript 1.2 (check out Netscape’s JS 1.2 documentation

if you want to find out more about these events - http://developer.netscape.com/library/documentation/

communicator/jsguide/js1_2.htm):

You can see that some new events have been implemented. We are going to have a look at some

of these events during this lesson.

First let’s see what the Resize event is for. With the help of this event we can detect whenever

the window is being resized by the user. The following script demonstrates this:

<html>

<head>

<script language="JavaScript">

window.onresize= message;

function message() {

alert("The window has been resized!");

}

</script>

</head>

<body>

Please resize the window.

</body>

</html>

Abort Focus MouseOut Submit

Blur KeyDown MouseOver Unload

Click KeyPress MouseUp

Change KeyUp Move

DblClick Load Reset

DragDrop MouseDown Resize

Error MouseMove Select

With the line

window.onresize= message;

we define the event handler. This means that the function message() ist being called as soon as

the window is being resized. You might not be familiar with this way of defining event handlers.

But this is nothing new in JavaScript 1.2. If you for example have a button object you can define

the event handler like this:

<form name="myForm">

<input type="button" name="myButton" onClick="alert(’Click event occured!’)">

</form>

But you could also write it like this:

<form name="myForm">

<input type="button" name="myButton">

</form>

...

<script language="JavaScript>

document.myForm.myButton.onclick= message;

function message() {

alert(’Click event occured!’);

}

</script>

You might think that the second alternative is a bit complicated. So why are we using it in the

first script? The problem is that the window object isn’t defined through a certain tag - so we’ll

have to use the second possibility.

Two important things: First you must not write

Second you must not write any brackets after message. If you write

window.onResize - i.e. you must use lower case.window.onresize= message()

the browser interprets

the function directly - we just want to define the event handler.

message() as a function call. But in this case we do not want to call

The Event object

A new Event object has been added to JavaScript 1.2. It contains properties which describe an

event. Every time an event occurs an Event object is passed to the event handler.

The following example shows an image. You can click it somewhere. An alert window will

come up and display the coordinates of the mouse event.

(The online version lets you test this script immediately)

Here is the source code:

<layer>

<a href="#" onClick="alert(’x: ’ + event.x + ’ y: ’ + event.y); return false;">

<img src="davinci.jpg" width=209 height=264 border=0></a>

</layer>

You can see that we are using the event handler onClick inside the

done with prior JavaScript versions. What is new is that we use event.x and event.y for creating

the output in the alert window. This is the Event object which we need in order to get to know

the mouse coordinates of the event.

I have put everything inside a

layer, i.e. in our case the image. Otherwise we would get the coordinates relative to the browser

window. (

The Event object has got the following properties (we will see some of these properties in the

next examples):

<a> tag as we would have<layer> tag. Like this we will get the coordinates relative to thisreturn false; is used here so that the browser does not follow the link)

Event capturing

One important feature is called event capturing. If someone for example clicks on a button the

onClick event handler of this button is being called. With the help of event capturing you can

achieve that your window, document or layer object captures the event before it is being handled

by the button object. Like this your window, document or layer object can handle the event before

it reaches its intended target.

Let’s have a look at an example in order to see what this is good for:

<html>

<head>

<script language="JavaScript">

Property Description

data

Array of URLs of the dropped objects when a DragDrop event occurs.

layerX

the Resize event this property represents the width of the browser window.

Horizontal position of cursor in pixel relative to layer. In combination with

layerY

Resize event this property represents the height of the browser window.

Vertical position of cursor in pixel relative to layer. In combination with the

modifiers

String specifying the modifier keys - ALT_MASK, CONTROL_MASK,

META_MASK

pageX

or SHIFT_MASKHorizontal position of cursor in pixel relative to browser window.

pageY

Vertical position of cursor in pixel relative to browser window.

screenX

Horizontal position of cursor in pixel relative to screen.

screenY

Vertical position of cursor in pixel relative to screen.

target

String representing the object to which the event was originally sent.

type

String representing event type.

which

ASCII-value of a pressed key or number of mouse button.

x

Synonymous to layerX.

y

Synonymous to layerY.

window.captureEvents(Event.CLICK);

window.onclick= handle;

function handle(e) {

alert("The window object captured this event!");

return true; // i.e. follow the link

}

</script>

</head>

<body>

<a href="test.htm">Click on this link</a>

</body>

</html>

(The online version lets you test this script immediately)

You can see that we do not define an event handler inside the <a> tag. Instead we use

window.captureEvents(Event.CLICK);

in order to capture the

not know the

Please note the writing of

several events you’ll have to separate them through a | - for example:

Click event through the window object. Normally the window object doesClick event. But through capturing the event we can redirect it to the window object.Event.CLICK. CLICK has to be in upper case. If you want to capture

window.captureEvents(Event.CLICK | Event.MOVE);

You can see that we use

handling function. This means that the browser is going to follow the link after the

return true; inside the function handle() which we defined as eventhandle()

function is being executed. If you write

If you define an

isn’t called. This is obvious as the window object captures the event before it reaches the link

object. If you define the

return false; instead, all following actions are being suppressed.onClick event handler inside the <a> tag you’ll realize that this event handlerhandle() function like this

function handle(e) {

alert("The window object captured this event!");

window.routeEvent(e);

return true;

}

the computer checks if there are other event handlers defined for this object. The variable e is

our Event object which is being passed to the event handling function.

You can also send an event directly to a certain object. For this purpose you can use the

handleEvent()

method. This looks like this:

<html>

<script language="JavaScript">

window.captureEvents(Event.CLICK);

window.onclick= handle;

function handle(e) {

document.links[1].handleEvent(e);

}

</script>

<a href="test.htm">Click on this link</a><br>

<a href="test.htm"

onClick="alert(’Event handler of second link!’);">Second link</a>

</html>

(The online version lets you test this script immediately)

All Click events are being sent to the second link - even if you do not click directly on the links!

The following script demonstrates that your script can react to key events. Just push a key in

order to see the script in action.

<html>

<script language="JavaScript">

window.captureEvents(Event.KEYPRESS);

window.onkeypress= pressed;

function pressed(e) {

alert("Key pressed! ASCII-value: " + e.which);

}

</script>

</html>

©1996,1997 by Stefan Koch

e-mail:skoch@rumms.uni-mannheim.de

http://rummelplatz.uni-mannheim.de/~skoch/

My german JavaScript-book: http://www.dpunkt.de/javascript/

V

OODOOS INTRODUCTION TO JAVASCRIPT

© 1996, 1997 by Stefan Koch

Part 12: Drag & Drop

What is drag & drop?

With the help of the new event model of JavaScript 1.2 and layers we can implement drag &

drop on our web-page. You’ll need at least Netscape Navigator 4.0 for this as we use JavaScript

1.2 features.

What is drag & drop? Some operating systems (like Win95/NT or MacOS) let you for example

erase files through dropping icons on a trash bin. What you do is you click on the icon of a file,

drag (i.e. you hold the mouse button down while moving the mouse) the icon to the trash bin

and drop it there.

The drag & drop we want to implement here is restricted to the web-page. So you cannot use

this code shown here in order to drag objects inside a HTML-page to your hard disk or something

like this. (Since Netscape Navigator 4.0 your script can react to an event called DragDrop

when somebody drops a file on your browser window - but this is not what we are going to talk

about in this lesson)

(The online version lets you test the example described in this lesson immediately. It shows three

boxes which can be moved with the help of the mouse)

You might also want to check out the example provided by Netscape. You can find it at this

address: http://home.netscape.com/comprod/products/communicator/user_agent_vacation.html

JavaScript does not support drag & drop directly. This means we cannot just specify a property

dragable (or whatever) in an image object. We have to write the code for this on our own. You’ll

see that this isn’t too difficult.

So what do we need? We need two things. First we have to register certain mouse events, i.e.

how do we know which object shall be moved to which position? Then we need to make up our

minds on how we can display the moving objects on the screen. Of course we will use the new

layer feature for defining different objects and moving them around on the screen. Every object

is represented through its own layer.

Mouse events with JavaScript 1.2

Which mouse events do we have to use? We don’t have a MouseDrag event - but we can achieve

the same through the events

event model. Without this event model we could not solve our task. I have talked about the new

event model in the last lesson. But let’s have a look at the important parts once again.

The user pushes the mouse button somewhere inside the browser window. Our script has to react

on this event and calculate which object (i.e. layer) was hit. We need to know the coordinates

of the mouse event. JavaScript 1.2 implements a new Event object which stores the coordinates

of a mouse event (besides other information).

Another important thing is called event capturing. If a user for example clicks on a button the

mouse event is sent directly to the button object. But in our case we want the window to handle

our event. So we let the window capture the mouse event, i.e. that the window object gets this

event and can react upon it. The following example demonstrates this (using the event

You can click somewhere inside the browser window. An alert window pops up and displays

the coordinates of the mouse event.

MouseDown, MouseMove and MouseUp. JavaScript 1.2 uses a newClick).

(The online version lets you test this script immediately)

This is the code for this example:

<html>

<script language="JavaScript">

<!--

window.captureEvents(Event.CLICK);

window.onclick= displayCoords;

function displayCoords(e) {

alert("x: " + e.pageX + " y: " + e.pageY);

}

// -->

</script>

Click somewhere inside the browser window.

</html>

First we tell the window object to capture the

Click event. We use the method captureEvent()

for this. The line

window.onclick= displayCoords;

defines what happens when a

reaction to a

this case).

Click event ocurs. It tells the browser to call displayCoords() as aClick event (Please note that you must not use brackets behind displayCoords indisplayCoords() is a function which is defines like this:

function displayCoords(e) {

alert("x: " + e.pageX + " y: " + e.pageY);

}

You can see that this function takes one argument (we call it e). This is the Event object which

is being passed to the

displayCoords() function. The Event object has got the properties pageX

and

displays these values.

pageY (besides others) which represent the coordinates of the mouse event. The alert window

MouseDown, MouseMove and MouseUp

As I already told you JavaScript does not know a

the events

example demonstrates the use of MouseMove. The actual coordinates of the mouse cursor

are displayed on the statusbar.

MouseDrag event. Therefore we have to useMouseDown, MouseMove and MouseUp in order to implement drag & drop. The following

(The online version lets you test this script immediately)

You can see that the code is almost the same as in the last example:

<html>

<script language="JavaScript">

<!--

window.captureEvents(Event.MOUSEMOVE);

window.onmousemove= displayCoords;

function displayCoords(e) {

status= "x: " + e.pageX + " y: " + e.pageY;

}

// -->

</script>

Mouse coordinates are displayed on the statusbar.

</html>

Please note that you have to write

case. When defining which function to call when the

use lower case:

Event.MOUSEMOVE, where MOUSEMOVE must be in upperMouseMove event occurs you have towindow.onmousemove=...

Now we can combine the last two examples. We want the coordinates of the mouse pointer to

be displayed when the mouse is being moved with pushed mouse button.

(The online version lets you test this script immediately)

The code for this example looks like this:

<html>

<script language="JavaScript">

<!--

window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);

window.onmousedown= startDrag;

window.onmouseup= endDrag;

window.onmousemove= moveIt;

function startDrag(e) {

window.captureEvents(Event.MOUSEMOVE);

}

function moveIt(e) {

// display coordinates

status= "x: " + e.pageX + " y: " + e.pageY;

}

function endDrag(e) {

window.releaseEvents(Event.MOUSEMOVE);

}

// -->

</script>

Push the mouse button and move the mouse. The coordinates are being

displayed on the statusbar.

</html>

First we tell the window object to capture the events

MouseDown and MouseUp:

window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);

You can see that we use the sign | (

by the window object. The next two lines define what happens when these events occur:

or) in order to define several events which shall be captured

window.onmousedown= startDrag;

window.onmouseup= endDrag;

The next line of code defines what happens when the window object gets a

MouseMove event:

window.onmousemove= moveIt;

But wait, we didn’t define

this event isn’t captured by the window object. So why do we tell the window object to call

Event.MOUSEMOVE in window.captureEvents()! This means thatmoveIt()

although this event never reaches the window object? The answer to this question can be

found in the function

startDrag() which is being called as soon as a MouseDown event occurs:

function startDrag(e) {

window.captureEvents(Event.MOUSEMOVE);

}

This means the window object captures the

pushed down. We have to stop capturing the

This does the function

MouseMove event as soon as the mouse button isMouseMove event when the MouseUp event occurs.endDrag() with the help of the method releaseEvents():

function endDrag(e) {

window.releaseEvents(Event.MOUSEMOVE);

}

The function

Now we have all elements for registering the events needed to implement drag & drop. We can

move forward to displaying the objects on the screen.

moveIt() writes the mouse coordinates to the statusbar.

Displaying moving objects

We have seen in previous lessons that we can create moving objects with the help of layers. All

we have to do now is to register which object the user clicked on. Then this object has to follow

the mouse movements. Here is the code for the example shown at the beginning of this lesson:

<html>

<head>

<script language="JavaScript">

<!--

var dragObj= new Array();

var dx, dy;

window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);

window.onmousedown= startDrag;

window.onmouseup= endDrag;

window.onmousemove= moveIt;

function startDrag(e) {

currentObj= whichObj(e);

window.captureEvents(Event.MOUSEMOVE);

}

function moveIt(e) {

if (currentObj != null) {

dragObj[currentObj].left= e.pageX - dx;

dragObj[currentObj].top= e.pageY - dy;

}

}

function endDrag(e) {

currentObj= null;

window.releaseEvents(Event.MOUSEMOVE);

}

function init() {

// define the ’dragable’ layers

dragObj[0]= document.layers["layer0"];

dragObj[1]= document.layers["layer1"];

dragObj[2]= document.layers["layer2"];

}

function whichObj(e) {

// check which object has been hit

var hit= null;

for (var i= 0; i < dragObj.length; i++) {

if ((dragObj[i].left < e.pageX) &&

(dragObj[i].left + dragObj[i].clip.width > e.pageX) &&

(dragObj[i].top < e.pageY) &&

(dragObj[i].top + dragObj[i].clip.height > e.pageY)) {

hit= i;

dx= e.pageX- dragObj[i].left;

dy= e.pageY- dragObj[i].top;

break;

}

}

return hit;

}

// -->

</script>

</head>

<body onLoad="init()">

<layer name="layer0" left=100 top=200 clip="100,100" bgcolor="#0000ff">

<font size=+1>Object 0</font>

</layer>

<layer name="layer1" left=300 top=200 clip="100,100" bgcolor="#00ff00">

<font size=+1>Object 1</font>

</layer>

<layer name="layer2" left=500 top=200 clip="100,100" bgcolor="#ff0000">

<font size=+1>Object 2</font>

</layer>

</body>

</html>

You can see that we define three layers in the

page is loaded the function

<body> part of this HTML-page. After the wholeinit() is called through the onLoad event handler in the <body> tag:

function init() {

// define the ’dragable’ layers

dragObj[0]= document.layers["layer0"];

dragObj[1]= document.layers["layer1"];

dragObj[2]= document.layers["layer2"];

}

The

in the

You can see that we use the same code as shown above in order to capture the mouse events:

dragObj array takes all layers which can be moved by the user. Every layer gets a numberdragObj array. We will need this number later on.

window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);

window.onmousedown= startDrag;

window.onmouseup= endDrag;

window.onmousemove= moveIt;

I have added the following line to the

startDrag() function:

currentObj= whichObj(e);

The function

the layer. If no layer has been hit it returns the value

value. This means that

the moment (or it is

In the function

With the help of these values we can check which object the user clicked on.

whichObj() determines which object the user clicked on. It returns the number ofnull. The variable currentObj stores thiscurrentObj represents the number of the layer which is being moved atnull if no layer is being moved).whichObj() we check the properties left, top, width and height for each layer.

Dropping objects

We have now everything we need in order to implement drag & drop. With our script the user

can drag around objects on our web-page. But we haven’t talked about dropping objects yet.

Let’s suppose that you want to create an online shop. You have several items which can be put

into a shopping basket. The user has to drag these items to the shopping basket and drop them

there. This means we have to register when the user drops an object on the shopping basket -

which means that he wants to buy it.

Which part of the code do we have to change in order to implement this? We have to check

which position the object has after a

function

a certain rectangle. If this is true you call a function which registers all items to buy (you might

want to put them inside an array). Then you could show the item inside the shopping basket.

MouseUp event - i.e. we have to add some code to theendDrag(). We could for example check if the coordinates of the mouse event lie inside

Improvements

There are several ways for improving our script. First we might want to change the order of the

layers as soon as the user clicks on one object. Otherwise it might a look a bit strange if you

move an object and it disappears behind another object. You can solve this problem by changing

the order of the layers in the

I don’t think that you’ll be satisfied by putting up red, green and blue boxes on your web page.

Add some cool graphics and the users will remember your page. You can place anything inside

the layer objects. So place a single

image

startDrag() function.<img> tag there if you want your object to appear as an.
 
  Menu Items
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  add
HOT TOPICS
MCA PROJECT DETAILS ------------------------------------- Jntu all Lab manuals ------------------------------------- Jntu Syllabus Books ------------------------------------- Paper presentations ------------------------------------- Seminars ------------------------------------- Campus Papers ------------------------------------- Competetive Exams GATE ------------------------------------- GRE ------------------------------------- TOEFL ------------------------------------- IELTS ------------------------------------- CAT ------------------------------------- GMAT ------------------------------------- Templates ------------------------------------- Students Resume Preparation tips ------------------------------------- Job zone(Interview questions) ------------------------------------- Google Adsence html code ------------------------------------- Web sites --------x--------------x-----------
  Advertisement

 


-----------------------------
  Offline Messages
  Adds
  Visitors Information
Today, there have been 119594 visitors (281296 hits) on this page!
-------------------------------------------------- This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free