Draggable Div Javascript | Draggable Div using Html Css JavaScript

Draggable Div Javascript | Draggable Div using Html Css JavaScript

Draggable Div Javascript | Draggable Div using Html Css JavaScript


Welcome🎉 to Code With Random blog. In this blog, we learn how we create Draggable Div Javascript. We use HTML, Css, and javascript for this Draggable Div Javascript. I hope you enjoy our blog so let’s start with a basic HTML structure for the Draggable Div Javascript.
 <div class="box">  
<span>Drag me</span>
</div>

There is all the HTML code for the Draggable Div Javascript. Now, you can see an output with Draggable Div Javascript then we write javascript for Draggable Div Javascript.

output

Draggable Div Javascript | Draggable Div using Html Css JavaScript

CSS code

 body {  
margin: 0;
height: 100vh;
background-image: radial-gradient(#e0dada,#dcefb6);
font-family: Arial, sans-serif;
}
.box {
position: fixed;
top: 35%;
left: 40%;
background: #eee;
box-shadow: #999 0px 8px 20px 0px;
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
user-select: none;
}

Css Updated output


Draggable Div Javascript | Draggable Div using Html Css JavaScript

Javascript code

 (() => {  
class Box {
constructor() {
this.box = document.querySelector(".box");
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
}
handleMouseDown() {
this.box.style.cursor = "move";
this.box.addEventListener("mouseup", this.handleMouseUp);
document.body.addEventListener("mousemove", this.handleMouseMove);
document.body.addEventListener("mouseleave", this.handleMouseUp);
}
handleMouseUp() {
this.box.style.cursor = "default";
document.body.removeEventListener("mousemove", this.handleMouseMove);
document.body.removeEventListener("mouseleave", this.handleMouseUp);
}
handleMouseMove(e) {
const boxRect = this.box.getBoundingClientRect();
this.box.style.top = `${boxRect.top + e.movementY}px`;
this.box.style.left = `${boxRect.left + e.movementX}px`;
}
init() {
this.box.addEventListener("mousedown", this.handleMouseDown);
}
}
const box = new Box();
box.init();
})();

Final output

Draggable Div Javascript | Draggable Div using Html Css JavaScript


Now that we have completed our javascript section,  Here is our updated output with javascriptHope you like the Draggable Div Javascript. you can see the output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you 🙏💕!

In this post, we learn how to create Draggable Div Javascript using simple HTML & CSS, and javascript. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning. 

Written by – Code With Random/Anki 



Leave a Reply