Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mouse location during mouse down?

How can I continuously get the position of the mouse whilst its button is being held down?

I know I can do:

<element onclick="functionName(event)"></element>
<script>
function functionName(e){
e.pageX
e.pageY
//do stuff
}
</script>

and I know you can use the onmousedown event, but how would I continuously get the position while the button is still held down?

Oddly I couldn't find this anywhere I looked.

like image 899
Max Hudson Avatar asked Jul 01 '12 13:07

Max Hudson


People also ask

What is on mouse down?

The onmousedown event occurs when a user presses a mouse button over an element. Tip: The order of events related to the onmousedown event (for the left/middle mouse button):

What is the difference between Mousedown and click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.

Does Mousedown work on mobile?

This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.

How can I tell if my mouse is down?

We can check if a mouse button is kept down by listening to the mousedown and mouseup events and mount how many times the mouse button is pressed down or lifted up.


2 Answers

Anyway, I'd suggest using mousemove event with check if which event property equals 1 (i.e. left mouse button pressed):

$("element").on("mousemove", function(e) {
    if (e.which == 1) {
        console.log(e.pageX + " / " + e.pageY);
    }
});​

DEMO: http://jsfiddle.net/HBZBQ/

like image 57
VisioN Avatar answered Nov 05 '22 23:11

VisioN


Here is a JSFiddle for you. You need to store the state of the mouse button in a variable.

jQuery:

$(document).ready(function() {
    $(document).mousedown(function() {
        $(this).data('mousedown', true);
    });
    $(document).mouseup(function() {
        $(this).data('mousedown', false);
    });

    $(document).mousemove(function(e) {
        if($(this).data('mousedown')) {
            $('body').text('X: ' + e.pageX + ', Y: ' + e.pageY);
        }
    });
});​

Here, I'm storing the mouse button's up or down state in document using $(document).data(). I could have used a global variable, but storing it this way makes the code a little cleaner.

In your $.mousemove() function, only do what you want if the mouse is down. In the code above, I'm simply printing the mouse's position.

like image 33
Bojangles Avatar answered Nov 06 '22 01:11

Bojangles