Move the element that can be dragged with the identifier X to the designated drop area with the identifier

I am attempting to create a function that will allow me to drag a draggable element and drop it into a designated container using their IDs. However, I am unsure of how to get started.

dropToContainer("myDraggable", "div3");

function dropToContainer(contentID, containerID)
{
//move draggable Element with contentID to the container with containerID
}

/* ----- DRAG & DROP FUNCTIONS ----------- */

function allowDropStatus(ev) {
    ev.preventDefault();
return false;
}

function dragInitialize(ev) {
   ev.dataTransfer.effectAllowed='move';
   ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
   return true;
}

function dropComplete(ev) {
    ev.preventDefault();
    var src = ev.dataTransfer.getData("Text");
   ev.target.appendChild(document.getElementById(src));
   ev.stopPropagation();
   return false;
}
#div1, #div2, #div3
{
  float:left; 
  width:280px; 
  height:180px; 
  margin:10px;
  padding:10px;
  border:1px solid #aaaaaa;
}
<div id="div1" ondrop="return dropComplete(event)" ondragover="return allowDropStatus(event)">
  <img id="myDraggable" src="https://www.webcodegeeks.com/wp-content/uploads/2015/12/WebCodeGeeks-logo.png" draggable="true" ondragstart="return dragInitialize(event)" width="250" height="150" id="drag1">
</div>

<div id="div2" ondrop="return dropComplete(event)" ondragover="return allowDropStatus(event)"></div>

<div id="div3" ondrop="return dropComplete(event)" ondragover="return allowDropStatus(event)"></div>

Would it be possible to achieve this functionality?

JSFIDDLE

https://jsfiddle.net/08u9zmau/ (Does not seem to work in JSFIDDLE)

Answer №1

Your progress has been commendable thus far.

One important factor to remember when connecting functions to DOM elements is that these functions absolutely must be defined before the DOM finishes rendering.

Whether you choose to include your script in the <head> section or right before the closing <body> tag, it is crucial that the functions are already available for use.

The JSfiddle link you shared may not function correctly because it loads the JS binding with the onLoad event trigger, meaning it happens as soon as the page opens. Adjusting this to load in the head or body will resolve the issue.

Answer №2

I successfully created the function, and it turned out to be quite straightforward:

function placeContentInContainer(contentID, containerID)
{
  var targetElement = document.getElementById(contentID);
  var clone = targetElement.cloneNode(true);

  document.getElementById(containerID).appendChild(clone);
  targetElement.parentNode.removeChild(targetElement);

}

/* ----- DRAG & DROP FUNCTIONS ----------- */

function allowDropAction(ev) {
  ev.preventDefault();
  return false;
}

function initializeDrag(ev) {
  ev.dataTransfer.effectAllowed='move';
  ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
  return true;
}

function completeDrop(ev) {
  ev.preventDefault();
  var src = ev.dataTransfer.getData("Text");
  ev.target.appendChild(document.getElementById(src));
  ev.stopPropagation();
  return false;
}
#div1, #div2, #div3
{
  float:left; 
  width:280px; 
  height:180px; 
  margin:10px;
  padding:10px;
  border:1px solid #aaaaaa;
}
<input type="button" value="move image" onclick="placeContentInContainer('myDraggable', 'div3');">
<div id="div1" ondrop="return completeDrop(event)" ondragover="return allowDropAction(event)">
  <img id="myDraggable" src="https://www.webcodegeeks.com/wp-content/uploads/2015/12/WebCodeGeeks-logo.png" draggable="true" ondragstart="return initializeDrag(event)" width="250" height="150" id="drag1">
</div>

<div id="div2" ondrop="return completeDrop(event)" ondragover="return allowDropAction(event)"></div>

<div id="div3" ondrop="return completeDrop(event)" ondragover="return allowDropAction(event)"></div>

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

Using regular expressions, you can conveniently extract text that is contained within paragraph tags

I attempted to use RegExp in JavaScript to extract text between paragraph tags, but unfortunately it isn't working... Here is my pattern: <p>(.*?)</p> The text I am trying to extract from is: <p> My content. </p> <img sr ...

What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not. ...

Adjust the color of the IconButton

I am trying to customize the color of an IconButton by setting it to red <IconButton variant='contained'> <StarBorderRoundedIcon color='red' /> </IconButton> However, when I try this, the red color ...

JavaScript function unable to access static file for image

I need assistance with dynamically displaying an image (a checkmark or "X") based on a variable. When I insert the image using a script directly in the HTML file, it functions correctly. However, when attempting to set the image from within the createEasyD ...

Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it. The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack ...

Placing a crimson asterisk beside the input field within Bootstrap

Trying to insert a red * at the end of my input field using bootstrap, but all my attempts so far have been unsuccessful. Is there a way to align the Currently experiencing this issue: https://i.stack.imgur.com/61pzb.png Code snippet: .required-after ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

Loss of Image Quality when Zooming out Canvas

I have developed a code to implement zoom-in and zoom-out functionality for a canvas image. However, I am facing an issue where the quality of the image deteriorates when zoomed more than once. I am using the canvas2image plugin to convert the canvas into ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

Tips for positioning the search form in the navbar header

My brand image and list with 2 glyph-icons & a search form in the navbar header are not aligning properly. The search form button keeps dropping to the line below. Does anyone know a CSS trick to keep it on the same line as the rest of the links? All the ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

What are some ways to direct users from one page to another without relying on server-side programming?

Is there a way to create a redirect page using jQuery or JavaScript? What is the process of writing client-side scripting code to redirect the browser from one page (page1) to another page (page n)? ...

JavaScript can be used to arrange a table in both ascending and descending order by simply clicking on the header

window.addEventListener('DOMContentLoaded', () => { let dir = "dsc"; th = document.getElementsByTagName('th'); for(let c=0; c < th.length; c++){ th[c].addEventListener('click',item(c)); } ...

Improving Image Performance in React.js

Seeking advice on the optimal performance of various image formats (such as SVG, PNG, JPEG) when displayed in a user interface. Which type is most efficient to render and what are the best practices for implementation to minimize loading times? ...

Navigating through events within React

I'm working on creating a login page, where upon clicking the submit button it should navigate to the Dashboard page. However, I seem to be encountering an issue with my code. After entering login details and clicking on the login button, the details ...

Exploring the Power of Jasmine Testing with Ternary Conditions

Imagine a scenario where we are working with the following snippet of JavaScript code. object = _.isUndefined(object) ? '' : aDifferentObject.property; Is it possible to write a Jasmine test that covers both scenarios? Do we need to use two se ...

I am having difficulty in crafting a sign-up form accurately

In my HTML file, I have a box that includes a sign-up form: <!-- sign up form --> <div id="cd-signup"> <form class="cd-form" action = "signup.php" > <?php echo "$error" ?> <p clas ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Unable to choose multiple sentences within an HTML Page displayed in a UIWebView

I am dealing with an HTML page structured as follows: <html> <body> <div id='0> <span id='0'>Hi </span> <span id='1'>How </span> <span id='2'>Are </span> <sp ...

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...