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
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.
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.
On the “mouse up” event, the value of drag variable is checked. If the value is true, a “drag” event has occurred and the output is displayed in the console. If the value is 'false' which means there has been no “mouse move” event which also implies that a “click” event had occurred.
To cause a MouseDown event for a form to occur, press the mouse button in a blank area or record selector on the form. To cause a MouseDown event for a form section to occur, press the mouse button in a blank area of the form section.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With