How to create a Draggable Element using HTML, CSS and JavaScript with source code

How to create a Draggable Element using HTML, CSS and JavaScript with source code
May 30, 2022

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';
}


Output:



Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates