Table of contents
1.
Introduction
2.
Drag and Drop Algorithm
3.
Potential Drop Targets (Droppables)
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Drag and Drop with Mouse

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Drag-and-drop functionality is defined as the act of selecting an item or piece of text, moving it (dragging), and then dropping it in another spot. Drag and Drop is a fantastic user interface option. Drag and Drop is a clear and simple way to conduct a variety of activities, from copying and moving documents (as in file managers) to ordering (dropping items into a cart).

There's a section regarding Drag and Drop in the modern HTML standard, with unique events like dragstart, dragend, and so on.

These events enable us to support advanced drag and drop scenarios, such as dragging a file from the OS file manager and dropping it into the browser window. The contents of such files can then be accessed by JavaScript. This blog will learn more about Drag and Drop with the mouse in detail. So, let’s move on with our topic without any further delay!

Also Read, Javascript hasOwnProperty

Drag and Drop Algorithm

The following is the basic Drag and Drop algorithm:

  1. On mousedown- If necessary, prepare the element for movement when the mouse is down (maybe create a clone of it, add a class to it or whatever).
  2. Then, on mousemove, change the left/top position using position: absolute.
  3. On mouseup- Perform all actions necessary to complete the drag and drop on mouseup.
     

Let's learn with the implementation of dragging a ball below:

ball.onmousedown = function(event) {
  // (1) Make absolute and on top by z-index to get ready to move.
  ball.style.position = 'absolute';
  ball.style.zIndex = 1000;
  // It should be moved directly into the body from any current parents.
  // to position it with relation to the body
  document.body.append(ball);
  // (pageX, pageY) coordinates are used to centre the ball.
  function moveAt(pageX, pageY) {
    ball.style.left = pageX - ball.offsetWidth / 2 + 'px';
    ball.style.top = pageY - ball.offsetHeight / 2 + 'px';
  }
  // Place our perfectly positioned ball beneath the pointer.
  moveAt(event.pageX, event.pageY);
  function onMouseMove(event) {
    moveAt(event.pageX, event.pageY);
  }
  // (2) On mousemove move the ball
  document.addEventListener('mousemove', onMouseMove);
  // (3) remove unneeded handlers, drop the ball
  ball.onmouseup = function() {
    document.removeEventListener('mousemove', onMouseMove);
    ball.onmouseup = null;
  };
};

 

When you run the code above, you'll notice something strange: the text "forks" at the start of the process, and you start dragging its clone. This occurs because the browser has its own drag and drop system for various items, such as photos, which runs automatically and competes with yours.

As a result, you must use the following code to disable it:

text.ondragstart = function () {
  return false;
};

 

Another crucial point to remember is that you track mouse movements on the document rather than the text. However, mouse moves are regularly triggered, but not for each pixel. As a result, your pointer may jump from the text wherever in the document's heart, as well as outside the window, after the transfer.

Source: Tutorial and Example

Potential Drop Targets (Droppables)

It is frequently necessary to move an element from one place to another (for example, a file into a folder). The solution is a little tough, but we'll go through it now.

A method called document.elementFromPoint(clientX, clientY) delivers the most nested element on specific window-relative coordinates (or null, in case the coordinates are located out of the window). It can be used to detect the potential droppable under the pointer in one of the mouse event handlers as follows:

// handles mouse event
text.hidden = true; // (*)hide the element we are dragging
let elemBelow = document.elementFromPoint(event.clientX, event.clientY);
// elemBelow - element which is below the text(it can be reset)
text.hidden = false;

Also read - Fork() System Call

Please keep in mind that the text should be hidden before the call (*). You will have a text on those coordinates in another way. So conceal it for a moment, then reveal it again. So, here's an enhanced version of onMouseMove that may be used to locate droppable elements:

<html>
  <head>
    <title>Title of the Document</title>
    <style>
      #text {
        cursor: pointer;
        cursor: pointer;
        width: 40px;
        height: 40px;
      }
    </style>
  </head>
  <body>
    <p id='text'>Drag the text</p>
    <script>
      let currentDroppable = null;
      text.onmousedown = function(event) {
        let shiftX = event.clientX - text.getBoundingClientRect()
          .left;
        let shiftY = event.clientY - text.getBoundingClientRect()
          .top;

 

Finally, the variable currentDroppable has a current drop target that can be used and highlighted. You can practice it by yourself with the help of an online javascript compiler.

Frequently Asked Questions

  1. What are drag and drop functionality?
    Drag-and-drop functionality is defined as the act of selecting an item or piece of text, moving it (dragging), and then dropping it in another spot.
     
  2. What does the method document.elementFromPoint(clientX, clientY) do?
    The method called document.elementFromPoint(clientX, clientY) delivers the most nested element on specific window-relative coordinates (or null, in case the coordinates are located out of the window).
     
  3. What happens at the mousedown event?
    Element is prepared for movement when the mouse is down (maybe create a clone of it, add a class to it or whatever).

Conclusion

In this article, we have extensively discussed Drag and Drop with mouse and its algorithm.

We hope that this blog has helped you enhance your knowledge regarding Drag and Drop with the mouse. If you want to learn more, check out our articles on Code studio.

Do upvote our blog to help other ninjas grow.

 

Happy Coding!

Live masterclass