Part 4 - How to capture and react to mouse events
So far we’ve seen how to dynamically create widgets and place them on the screen, the only problem is that the user can’t move them around. In order to enable dragging of widgets, we have to first learn how to capture mouse event.
A simple example (click here to see it in action):
var firefox=document.getElementById&&!document.all; //detect browser
document.onmousemove=mouseMove; //capture mouse move events
function mouseMove(e){ //define what to do when mouse moves
var str;
if (firefox)
str="x="+e.clientX+", y="+e.clientY;
else
str="x="+event.clientX+", y="+event.clientY;
document.title=str;
}
First we detect the browser the user is using. This is important because Firefox and IE handle events differently.
We then instruct the browser to call our mouseMove function (document.onmousemove=mouseMove) each time the mouse is moved. (A common mistake here is to use document.onmousemove=mouseMove() - but the ‘()’ should not be used).
In Firefox, each time the mouse moves the browser generates an event object and passes it on to the function handling the event. In our case, the mouseMove function receives the event via the e variable. the X and Y coordinates are stored in the clientX and clientY attributes of the event object.
IE uses a global event: event. So every time the mouse moves, our function gets called but nothing is passed to the function. Instead we have to access the global event object (e.g. event.clientX) to get the coordinates.
the coordinates are displayed in the browser’s title bar.
