I have a java Script function that i want to call whenever mouse moves so whats the way to call it in java script. Thanks
A:
You have to have an html element that will fire the event. For instance
<div onmousemove="foo()"></div>
If you want it to happen all over the page I believe that putting the event on the body tag will work but I am not sure.
Here is a reference for the event http://www.w3schools.com/jsref/event_onmousemove.asp
Samuel
2009-10-29 01:03:14
+3
A:
Well, you didn't really provide an element onto which you want to attach the handler, but here's how to do it with the body element:
<html>
<head>
<script type="text/javascript">
function move() {
alert("Your mouse moved!");
}
</script>
</head>
<body onmousemove="move()">
<div>Test</div>
</body>
</html>
Salty
2009-10-29 01:03:21
A:
Samuel and Salty both provide a bad way of attaching event listeners! Separate your presentation from the application, please!
function move(){
//do something on mouse move
}
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
oldonload();
func();
}
}
}
function init(){
var body = document.getElementsByTagName('body')[0];
addEvent(body, 'mousemove', move);
}
addLoadEvent(init);
Thanks to Dustin Diaz for event handling functions - or use your favourite library.
David Caunt
2009-10-29 01:11:13