JSFiddle - React, Tailwind, and code Playground
by Artem
HTML
<img draggable="true" src="https://pngimg.com/upload/small/basketball_PNG1096.png" width="100" alt="" id="img">
<div id="target"></div>
CSS
body {
margin: 0;
}
img {
position: absolute;
border: 1px solid #000;
cursor: pointer;
}
#target {
margin-left: auto;
width: 100px;
height: 100px;
background-color: #c9c9c9;
border: 5px solid #b1b1b1;
}
JavaScript
'use strict';
const img = document.images[0];
const target = document.getElementById('target');
let x, y;
img.ondragstart = function(e) {
e.dataTransfer.setData('id', e.target.id);
console.log('ok');
}
img.ondragend = function(e) {
console.log('end');
}
target.addEventListener("dragover", function(event) {
event.preventDefault();
});
target.ondrop = function(e) {
console.log('dropped');
}
img.ondragover
img.addEventListener('mousedown', function(e) {
//console.log(e.clientX, e.clientY);
img.addEventListener('mousemove', onmove);
x = e.offsetX;
y = e.offsetY;
console.log('down');
});
function onmove(e) {
img.style.left = e.clientX - x + 'px';
img.style.top = e.clientY - y + 'px';
console.log('moving');
}
img.addEventListener('mouseup', function(e) {
//console.log(e.clientX, e.clientY);
console.log('up');
img.removeEventListener('mousemove', onmove);
});