6

Here is an example fiddle were you click on the red box and it shows the coordinates of your pointer relative to the box.

How am I able to modify this script to allow the coordinates to update if I click and drag? Allowing the coordinates to update live as I am holding down the click and moving the mouse.

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

Code from Fiddle:

$('#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've tried a few different things but nothing has worked so far and can't find another question that's similar apart from one without an answer.

Thanks

Jack
  • 3,271
  • 11
  • 48
  • 57
  • may be this will help you http://stackoverflow.com/questions/4127118/can-you-detect-dragging-in-jquery – Nishit Maheta Apr 04 '15 at 12:34
  • Thank you but the answer doesn't update live as you're dragging, instead it updates after the click is over by the looks of it. – Jack Apr 04 '15 at 12:35

1 Answers1

5

simply set a flag on mouse down, and then check for it on mouse move. theres your drag:

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>
Banana
  • 7,424
  • 3
  • 22
  • 43
  • 1
    dragging is simply when the mouse moves as the mouse button is being held down. this is exactly what my example does... test it. unless you need the coordinates to update even if the mouse leaves the red box, in which case let me know and i will update my code. – Banana Apr 04 '15 at 12:40