Home
JavaScript Moveable Draggable Div
Copy and past the code to a HTML file, play with it and work the rest out for yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
.XXX{
border-style:solid;
border-width:2px;
padding:20px;
width:fit-content;
position:absolute;
}
</style>
</head>
<body>
<div id="XXX" class="XXX" onmousedown="DStart(event)" onmouseup="DEnd(event)">
Drag And Drop Me Around The Screen
</div>
<script>
var xxx = document.getElementById('XXX');
var offTop = 0;
var offLeft = 0;
var onOff = false
document.onmousemove = function (event) {
if (onOff == true) {
console.log("MMOve")
xxx.style.top = (event.clientY - offTop) + 'px';
xxx.style.left = (event.clientX - offLeft) + 'px';
}
}
function DStart(e) {
offTop = e.clientY - xxx.offsetTop;
offLeft = e.clientX - xxx.offsetLeft;
onOff = true;
}
function DEnd(e) {
onOff = false;
}
</script>
</body>
</html>
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home