Looking for a solution to drag an element after the "mouseup" event.
As you know dragging occurs when it recieves "mousedown" and "mousemove" events.
How can I achieve dragging with the "mouseup" event? (When click is realised)?
https://codepen.io/pklauzinski/pen/rxroyL
// Implement drag and drop for the image
$('.box').on('mousedown', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('mouseup', function() {
$window.off('mousemove.drag');
});
});
You can always use the $('.box').on('click', function(e) {
method... that could make it, but keep in mind you would have to add an other on click or doubleclick to disable, also, it's quite a weird behaviour
Sample explanation of what I mean
// Implement drag and drop for the image
$('.box').on('click', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('mousedown', function() {
$window.off('mousemove.drag');
});
});
This is how I would do it though
// Implement drag and drop for the image
$('.box').on('mousedown', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('click', function() {
$window.off('mousemove.drag');
});
});