user5861285 user5861285 - 2 months ago 8
jQuery Question

How to get mouseposition (pageX , pageY) during mousemove with pressed mousebutton

I need the actual mouseposition of every move only when the mousebutton is pressed.

I used the following:

var time, click= $( '#foo li' );
click.mousedown(function(e){
time= setInterval(function(){
$( '#foo li' ).mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
$( ".output" ).empty();
$( ".output' ).append( msg );
});
}, 500);
return false;
});

$(document).mouseup(function(e){
clearInterval(time);
$(window).unbind( 'mousemove');
return false;
});


It works fine: every position will be printed in 'output'. But the mouseup Event will not stop the mousemove function. What could be the problem?

Update:

Sorry,im just beginner...

I tried it this way and it works fine. Is there a better way to do this so tell me...

var down = false;
$('#foo').mousedown(function(){
down = true;
});

$(document).mouseup(function(){
down = false;
})

$('#foo').mousemove(function(e){
if(down == false) return;
$('.output').empty();
$('.output').append(e.pageX +' & ' + e.pageY);
});

Answer

Try this:

var click= $( '#foo li' );
click.mousedown(function(e){
  $( '#foo li' ).mousemove(function( event ) {
    var msg = "Handler for .mousemove() called at ";
    msg += event.pageX + ", " + event.pageY;
    $( '.output' ).empty();
    $( '.output' ).append( msg );
  });
});

$(document).mouseup(function(e){
  $( '#foo li' ).unbind( 'mousemove');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<div id="foo">
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
</div>

Comments