060
Make HTML Element Draggable with Bar
This is an extended version of previous example Make Html Element Draggable, to make an html element draggable by dragging a bar.
Codebase
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Draggable</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="draggable-object">
<div class="draggable-subject">Draggable</div>
</div>
<script src="app.js"></script>
</body>
</html>
style.css
@charset "utf-8";
.draggable-object {
position: absolute;
}
.draggable-subject {
cursor: grab;
}
.draggable-subject:active {
cursor: grabbing;
}
/* Only for demo */
html, body {
width: 100%;
height: 100%;
}
body {
margin: 0;
font-family: sans-serif;
}
.draggable-object {
width: 160px;
height: 160px;
border: 1px solid #ddd;
border-radius: 2px;
display: inline-block;
}
.draggable-subject {
background: #f0f0f0;
padding: 4px 8px;
}
app.js
const draggableObject = document.querySelector('.draggable-object');
const draggableSubject = document.querySelector('.draggable-subject');
const unit = 'px'
let diffX, diffY
function startDrag(e) {
e.preventDefault()
const { x, y } = draggableObject.getBoundingClientRect()
diffX = e.x - x
diffY = e.y - y
document.onmousemove = drag
}
function drag(e) {
e.preventDefault()
draggableObject.style.left = (e.x - diffX) + unit
draggableObject.style.top = (e.y - diffY) + unit
}
function endDrag() {
document.onmousemove = null
}
draggableSubject.onmousedown = startDrag
draggableSubject.onmouseup = endDrag