How can I determine start and stop points for mouse cursor?
Let's say the user starts to move mouse and stop at somewhere on the browser. How can I determine start and stop point with Javascript/jQuery?
Start point is easy, I can get it with mousemove
event but what about stop point?
I can't use mouseenter
or mouseleave
events because my playground is window or document itself.
Solution 1:
using a combination of setTimeout and clearTimeout. If the user doesn't move for x amount of seconds then it means that he stopped.
Here I wrote you an example:
<script type="text/javascript">
var lastMove = 0;
var lastTimeout = 0;
jQuery(document).ready(function () {
$(document).mousemove(function (e) {
$('#status').html(e.pageX + ', ' + e.pageY);
var currentMove = (new Date()).getTime();
if (lastTimeout != 0) {
clearTimeout(lastTimeout);
}
if (currentMove - lastMove > 1500)
{ alert('started'); }
lastMove = currentMove;
lastTimeout = setTimeout(function () {
var currentMove = (new Date()).getTime();
if (currentMove - lastMove > 1500)
{ alert('stopped'); }
}, 1510);
});
})
</script>
<h2 id="status">
0, 0
</h2>