JSFiddle - React, Tailwind, and code Playground
by Tan
HTML
<div id="container">
<div id="mydiv">
<img src="http://www.hloe.co.uk/world-map.gif">
</div>
</div>
<h2>Drag the image</h2>
Xtop = <span id="ptop"></span><br>
Yleft = <span id="pleft"></span>
CSS
#container {
width: 300px;
height: 300px;
margin: auto;
position: relative;
overflow: hidden;
border: 1px solid #999999;
}
#mydiv {
cursor: move;
position: absolute;
background-color: #dedede;
}
#mydiv img {
display: block;
}
JavaScript
function id(x) {var y = document.getElementById(x);return y;}
/* Don't need this */
var ptop = id('ptop');
var pleft = id('pleft');
var mapBg = id('container').offsetWidth;
var start = id('mydiv');
var mapW = start.offsetWidth;
var mapH = start.offsetHeight;
start.style.left = "-" + ((mapW / 2) - (mapBg / 2)) + "px";
start.style.top = "-" + ((mapH / 2) - (mapBg / 2)) + "px";
//Make the DIV element draggagle:
dragElement(start);
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (elmnt) {
/* if present, the header is where you move the DIV from:*/
elmnt.onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
if (elmnt.offsetLeft < (mapBg-mapW)) {
elmnt.style.left = (mapBg-mapW) + "px";
}
if (elmnt.offsetLeft > 0) {
elmnt.style.left = 0 + "px";
}
if (elmnt.offsetTop < (mapBg-mapH)) {
elmnt.style.top = (mapBg-mapH) + "px";
}
if (elmnt.offsetTop > 0) {
elmnt.style.top = 0 + "px";
}
/* Don't need this */
ptop.innerHTML = (elmnt.offsetTop) + "px";
pleft.innerHTML = (elmnt.offsetLeft) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
...