A draggable element is an element in a web page that can be dragged on the screen. Using HTML, CSS, and JavaScript, you can create a draggable element easily.
Check out the source code for Draggable Element:
HTML Code:
<div class="container">
<div class="drag" id="drag">
Dragg Me!
</div>
</div>
CSS Code:
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #252525;
font-family: Arial, Helvetica, sans-serif;
}
.container{
width: 500px;
height: 500px;
border: 1px solid #ff2f90;
border-radius: 30px;
display: flex;
justify-content: center;
align-items: center;
}
.drag{
width: 100px;
background-color: #ff2f90;
cursor: pointer;
color: white;
text-align: center;
padding: 30px;
border-radius: 30px;
}
JavaScript Code:
window.onload = dragListeners();
function dragListeners() {
document.getElementById('drag').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp() {
window.removeEventListener('mousemove', moveDiv, true);
}
function mouseDown(e) {
const div = document.getElementById('drag');
div.setAttribute("cursor", "pointer");
window.addEventListener('mousemove', moveDiv, true);
}
function moveDiv(e) {
const div = document.getElementById('drag');
div.setAttribute("cursor", "pointer");
div.style.position = 'absolute';
div.style.top = e.clientY + 'px';
div.style.left = e.clientX + 'px';
}