A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ball gets removed from the left panel while being dragged. What I want is for the ball to only be draggable/movable to the right panel, without the possibility of going back to the left panel. Below is the code snippet:

let currentDroppable = null;

ball.onmousedown = function(event) {

  let shiftX = event.clientX - ball.getBoundingClientRect().left;
  let shiftY = event.clientY - ball.getBoundingClientRect().top;

  ball.style.position = 'absolute';
  ball.style.zIndex = 1000;
  document.body.append(ball);

  moveAt(event.pageX, event.pageY);

  function moveAt(pageX, pageY) {
    ball.style.left = pageX - shiftX + 'px';
    ball.style.top = pageY - shiftY + 'px';
  }

  function onMouseMove(event) {
    moveAt(event.pageX, event.pageY);

    ball.hidden = true;
    let elemBelow = document.elementFromPoint(event.clientX, event.clientY);
    ball.hidden = false;

    if (!elemBelow) return;

    let droppableBelow = elemBelow.closest('.droppable');
    if (currentDroppable != droppableBelow) {
      if (currentDroppable) { // null when we were not over a droppable before this event
        leaveDroppable(currentDroppable);
      }
      currentDroppable = droppableBelow;
      if (currentDroppable) { // null if we're not coming over a droppable now
        // (maybe just left the droppable)
        enterDroppable(currentDroppable);
      }
    }
  }

  document.addEventListener('mousemove', onMouseMove);

  ball.onmouseup = function() {
    document.removeEventListener('mousemove', onMouseMove);
    ball.onmouseup = null;
  };

};

function enterDroppable(elem) {
  elem.style.background = 'pink';
}

function leaveDroppable(elem) {
  elem.style.background = '';
}

ball.ondragstart = function() {
  return false;
};
#gate {
  cursor: pointer;
  margin-bottom: 100px;
  width: 83px;
  height: 46px;
  border: 1px solid;
}

#ball {
  cursor: pointer;
  width: 40px;
  height: 40px;
}
<div style="float:left;border: 1px solid;width: 15%;">Left Pannel<img src="https://en.js.cx/clipart/ball.svg" id="ball"></div>
<div style="float: left;border: 1px solid;width: 80%;height: 1000px;">Right Panel</div>

Answer №1

    <head>
      <script>
        function allowDrop(event) {
          event.preventDefault();
        }
    
        function drag(event) {
          event.dataTransfer.setData("text", event.target.id);
        }
    
        function drop(event) {
          event.preventDefault();
          var data = event.dataTransfer.getData("text");
          event.target.appendChild(document.getElementById(data));
        }
      </script>
    </head>

<body>  
  <div style="float:right;border: 1px dashed;width: 20%;" id="box1" ondrop="drop(event)" ondragover="allowDrop(event)">
    Left Box
    <img id="sphere" src="https://en.js.cx/clipart/sphere.svg" draggable="true" ondragstart="drag(event)">
  </div>
  <div id="box2" ondrop="drop(event)" ondragover="allowDrop(event)"
    style="float: left;border: 1px solid;width: 75%;height: 800px;">Right Box</div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

Applying a gradient overlay to an image using CSS

Feeling a bit frustrated with this issue. I'm working on my Joomla website utilizing Phoca Gallery, and the code it generates includes the following: <img class="pg-image" src="/images/phocagallery/other/thumbs/phoca_thumb_m_something.jpg" alt="So ...

How can I update two divs simultaneously with just one ajax call?

Is there a way to update 2 divs using only one ajax request? The code for updating through ajax is in ajax-update.php. <?php include("config.inc.php"); include("user.inc.php"); $id = $_GET['id']; $item = New item($id); $result = $item->it ...

To prevent the background image (blue border) from shifting, I need to extract the list item element without causing the image to

Having trouble with the side borders on my navbar. I've used a background image for the border (blue line) in the list item of the navbar. Is there a way to move down two specific list items slightly, like shown in my screenshot? I need to bring down ...

Adjusting icons based on the length of the text

When I have a title text and an icon, I want to align the icon to the left if the title fits on a single line. However, if the title spans multiple lines, then I need to align the icon to the top. I recently discovered a solution that involves using Javas ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

What is the correct way to pass data to a sibling component while making sequential asynchronous calls?

Currently, I am developing a hackernews clone in order to practice my ReactJS skills. Initially, I am constructing it solely with React and intend to integrate Redux at a later stage. Here is the component structure of the project: --main |--menubar | ...

Redirecting users based on their type - Vue router

Seeking assistance as a novice in vue. Building an app with firebase-connected login. Want to utilize vue-router for user redirections. Goal: Redirect "admin" users to "/admin", others to "/", and non-logged-in users to "/login". Sharing parts of my code: ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

Could the addition of iframes enhance the efficiency of websites containing a vast amount of DOM elements?

When dealing with websites that have a massive amount of DOM elements, could there be any performance advantages to displaying some content within an iframe? For instance, the project I am currently involved in features a large HTML-based tree structure ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

Ways to retrieve the file name from the content-disposition header

I received a file through an AJAX response. I am trying to extract the filename and file type from the content-disposition header in order to display a thumbnail for it. Despite conducting multiple searches, I have been unable to find a solution. $(". ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Style selector for dynamic drop-down menus

import React, { Component } from "react"; export default class FontChanger extends Component{ constructor(props){ super(props); this.state ={ selectedFont: "", currentFont: "", }; this.handleFon ...

What is the main file that vue-cli-service utilizes for entry?

Interested in a project utilizing vue, webpack, babel, npm? You can launch it with npm run server. While exploring how this command functions, I came across vue-cli-service serve in the package.json file. But how exactly does vue-cli-service initialize ...

display information in a structured table format

I am in need of HTML code that will render headers aligned above corresponding values when displayed. header1 header2 header3 List item 1 value111 value112 value113 value121 valueb122 valueb123 List item 2 value211 value212 value213 value221 valueb2 ...

Implementing the MVC pattern in the app.js file for a Node.js and Express web application

After completing several tutorials on nodejs, mongodb, and express, I have gained a solid understanding of the basics such as: The main controller file being app.js. Third party modules stored in their designated node_modules directory. Template files pl ...

What is the best way to determine if an AJAX response is of the JavaScript content type?

There are multiple forms in my system, each returning different types of data. I need to be able to distinguish between a simple string (to display in the error/status area) and JavaScript code that needs to be executed. Currently, this is how I'm ha ...