I am having some trouble understanding how to get a variable to work in my .onmouseup
event.
I have a .onmousemove
event that defines a local variable that is, for example the distance the mouse has moved since .onmousedown
. I want to use that information in a function that executes .onmouseup
, however, I can't get it there. Here are the relevant bits of code:
document.onmousedown = function(){
var mouseStart = [event.pageX,event.pageY];
document.onmousemove = function(){
var dist = Math.sqrt(Math.pow(event.pageY-mouseStart[1],2)+Math.pow(event.pageX-mouseStart[0],2));
document.onmouseup = function() {
global_function(dist);
document.onmousemove = null;
}
}
}
I don't understand why mouseStart
is accessible but I get the get the error that dist is undefined.
I have other variables that also need to be passed which cannot be redefined during .onmouseup
.
I think you'll want add the onmouseup event handler inside the onmousedown handler. The mousemove event fires something like 50 times per second in some browsers, so you repeatedly add and remove the mouse up/down events. Then you'll want to declare dist
inside the mousedown handler.
For browser compatibility, the event
object gets passed in the event handler by many browsers, and in others it is a global variable. A simple event = window.event || event
coupled with declaring an event
argument to the handler does the trick.
document.onmousedown = function(event) {
event = window.event || event;
var mouseStart = [event.pageX,event.pageY];
var dist;
document.onmouseup = function() {
global_function(dist);
document.onmousemove = null;
};
document.onmousemove = function(ev) {
ev = window.event || ev;
dist = Math.sqrt(Math.pow(ev.pageY-mouseStart[1],2)+Math.pow(ev.pageX-mouseStart[0],2));
};
};