Offset is not updated on mousedown event while holding click and drag

Here is an example of a violin: you click on the red frame and on it indicate the coordinates of your pointer relative to the field.

How do I change this script to allow coordinates if I click and drag? Allowing coordinates to be updated live when I hold the click and move the mouse.

http://jsfiddle.net/lonesomeday/5qxtL/2/

Code from script:

$('#target').mousedown(function(e) { var offset = $(this).offset(), imgLeft = e.pageX - offset.left, imgTop = e.pageY - offset.top; $('#result').text('Mouse clicked x = ' + imgLeft + ' Y = ' + imgTop); }); 

I tried several different things, but so far nothing has worked and cannot find another question that is similar except one without an answer.

thanks

+5
source share
1 answer

just set the mouse flag down and then check it when moving the mouse. theres your resistance:

 var mouseDownFlag = false; $('#target').mousedown(function(e) { mouseDownFlag = true; var offset = $(this).offset(), imgLeft = e.pageX - offset.left, imgTop = e.pageY - offset.top; $('#result').text('Mouse clicked x = ' + imgLeft + ' Y = ' + imgTop); }); $('#target').mouseup(function(e) { mouseDownFlag = false; }); $('#target').mousemove(function(e) { if (mouseDownFlag) { var offset = $(this).offset(), imgLeft = e.pageX - offset.left, imgTop = e.pageY - offset.top; $('#result').text('Mouse clicked x = ' + imgLeft + ' Y = ' + imgTop); } }); 
 div { width: 200px; height: 100px; position: relative; left: 30px; top: 15px; background-color: #f00; } #result { background-color: #fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="target">My target div</div> <div id="result"></div> 
+4
source

All Articles