Using Layer-based Events

Pre-requisite: You should read the Document Mouse Events lesson before reading this one.

Using the elm property you can define events for your layer such as onMouseOver, onMouseOut, onMouseDown, onMouseUp, onMouseMove, and onClick.

In Netscape you can't mark up the event handlers like you can with an anchor:

<DIV ID="divName" onMouseDown="/*your code*/"></DIV>

However, you can define handlers directly using JavaScript. For Netscape you use:

document.layer[id].onmouseover = downHandler

For IE:

document.all[id].onmouseover = downHandler

For a cross-browser solution you can define the handlers using the DynLayer elm property (which points to the actual element rather than the CSS properties):

objectName.elm.onmousedown = layerDownHandler
objectName.elm.onmouseup = layerUpHandler
objectName.elm.onmouseover = layerOverHandler
objectName.elm.onmouseout = layerOutHandler
objectName.elm.onmousemove = layerMoveHandler
objectName.elm.onclick = layerClickHandler
if (is.ns) objectName.elm.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP | Event.MOUSEMOVE)

Make sure you define the mouse events using all lowercase. The handler names can be whatever you choose.

For Netscape you have to manually capture the events that you want to use. You can see in the captureEvents line how to set them up. If you don't need one of them just remove it from the command. You do not need to capture the mouseOver and mouseOut events as it appears they are captured by default.

Another way to define your handlers is to use the new Function() command. Doing it this way you can pass parameters quite easily.

objectName.elm.onmousedown = new Function("layerDownHandler('my string!')")
if (is.ns) objectName.elm.captureEvents(Event.MOUSEDOWN)

function layerDownHandler(string) {
	status = string

There is yet another way to pass parameters, you can temporarily define sub-properties to the dynlayer event property, and retrieve them in the handler function:

objectName.elm.string = "my string!"
objectName.elm.onmousedown = layerDownHandler
if (is.ns) objectName.elm.captureEvents(Event.MOUSEDOWN)

function layerDownHandler() {
	status = this.string

Using Mouse Coordinates

In the handler functions you can retrieve the location of the mouse by using the following commands:

var x = (is.ns)? e.layerX:event.offsetX
var y = (is.ns)? e.layerY:event.offsetY

The x and y variables can then be used to do whatever you wish. For example, here's some code that will display the location of the mouse while over the layer:

function init() {
	mylayer = new DynLayer("mylayerDiv")
	mylayer.elm.onmousemove = layerMoveHandler
	if (is.ns) mylayer.elm.captureEvents(Event.MOUSEMOVE)

function layerMoveHandler(e) {
	var x = (is.ns)? e.layerX:event.offsetX
	var y = (is.ns)? e.layerY:event.offsetY
	status = x+","+y

Example: dynlayer-mouseevents1.html [source]

The Dynamic Layer Object API

Home Next Lesson: DynLayer Methods
copyright 1998 Dan Steinman