Retrieving elements under the mouse

by kalai 2008-04-30 19:54:17

Steps that need to be done:
* Write an event handler (a function) to handle mouse events.
* Assign the function to intercept the desired mouse event(s).
* Retrieve the element from within the event handler. When a mouse event is fired, the element which fires the event will be one of the member of the event handler parameter.



Calling the event handler function

Eventhandlerfunction is triggered when the mouse is pressed down.
<body onMouseDown="javaScript:mouseEventHandler(event);">
<table border=1><tr><td>bla bla bla</td></tr></table>



Retrieving the element

whenever an event is fired, an event object is passed implicitly to the event handler. Within this event object, there is a parameter. This parameter is a pointer to the element that fired the event. In Internet Explorer, this parameter is: event.target; while in Mozilla browsers (such as Netscape and Internet Explorer), it is: event.srcElement.

Once you have access to the element, there are many things that can be done with it. For starter, the sample code below prints the nodeName of the element (nodeName is the html tag of the element, such as "IMG", "TABLE", "INPUT", etc):
<script language="javascript">
function mouseEventHandler(mEvent)
{
// Internet Explorer
if (mEvent.srcElement)
{
alert(mEvent.srcElement.nodeName);
}
// Netscape and Firefox
else if (mEvent.target)
{
alert(mEvent.target.nodeName);
}
}
</script>

Tagged in:

1460
like
0
dislike
0
mail
flag

You must LOGIN to add comments