Celebrombore
Celebrombore

Reputation: 170

Using mousedown-position in mouseup-event

Hey guys I am trying an easy custom-made drag and drop system of an element. I wanna use the mousedown and mouseup event for that.

My problem is that I dont know how to get the mousedown-position in the mouseup-event.

div.mousedown(function (e) {
  var cursorDown = e.pageX;
}).mouseup(function (e) {
  alert(cursorDown)
})

I tried to modify the solution from here to only get the first and last value, but I failed: How can I retrieve all mouse coordinates between mousedown to mouseup event

I appreciate every tip ypu can give me

Thank you in advance

Upvotes: 0

Views: 1646

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

You could use the data-* attribute with the jQuery's .data() Method

$('#box').on({
  mousedown(evt) {
    $(this).data('xyDn', {x: evt.pageX, y: evt.pageY});
  },
  mouseup(evt) {
    const xyDn = $(this).data('xyDn');
    const xyUp = {x: evt.pageX, y: evt.pageY};
    console.log(`
      DN = x:${xyDn.x} y:${xyDn.y}
      UP = x:${xyUp.x} y:${xyUp.y}
    `);
  },
});
html, body {
  height: 100%;
  margin: 0;
}

#box {
  width: 100vw;
  height: 100vh;
}
<div id="box"></div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28611

You need to store it outside the event handler.

Either in a variable (if they'll only ever be one or it's wrapped in a plugin) - or, to keep it self-contained, against the item:

div.mousedown(function (e) {
  $(this).data("cursorDown", e.pageX)
}).mouseup(function (e) {
  var cursorDown = $(this).data("cursorDown")
  alert(cursorDown)
})

To modify the other solution:

var allPoints = [];
div.mousedown(function (e) {
  $(this).on("mousemove", trackPoints); 
}).mouseup(function (e) {
  $(this).off("mousemove", trackPoints);

  var cursorDown = allPoints[0];
  allPoints = [];  // clear drag details
});

function trackPoints(e) {
  allPoints.push({ x: e.pageX, y: e.pageY });
}

or, using a variable

var cursorDown = {};
div.mousedown(function (e) {
  cursorDown = { x: e.pageX, y: e.pageY };
}).mouseup(function (e) {
  alert(cursorDown)
});

Upvotes: 1

Related Questions