Drag and Drop in HTML5: Resize Div Automatically upon Transfer

I have implemented a drag and drop feature that transfers images into three different divs. However, I am facing an issue where the dimensions of the div do not adjust according to the image inserted, causing them to not fit in a single box.

Additionally, I am wondering if it is possible to append only the alt text of each image so that they all fit properly?

<!DOCTYPE HTML>
<html>
<head>
<style>
div {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>


<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
  <img id="drag2" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
  <img id="drag3" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">


</body>
</html>

Answer №1

To adjust the dimensions of the div once the image is dropped, you can utilize JavaScript to remove padding from the CSS and ensure that the div aligns properly with the image. Here's an example:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  //console.log(ev.target.id)
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var img = document.getElementById(data);
  ev.target.appendChild(img);

  // Set the div width & height based on the image dimensions
  ev.target.style.width = parseInt(img.width) + 'px';
  ev.target.style.height = parseInt(img.height) + 'px';
}
div {
  border: 1px solid #aaaaaa;
  width: 350px;
  height: 70px;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br/>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br/>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="https://images.unsplash.com/photo-1507146426996-ef05306b995a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=336&q=69" draggable="true" ondragstart="drag(event)">
<img id="drag2" src="https://images.pexels.com/photos/33053/dog-young-dog-small-dog-maltese.jpg?auto=compress&cs=tinysrgb&dpr=2&w=336&h=69" draggable="true" ondragstart="drag(event)">
<img id="drag3" src="https://images.pexels.com/photos/257540/pexels-photo-257540.jpeg?auto=compress&cs=tinysrgb&h=69&w=336" draggable="true" ondragstart="drag(event)">

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

Prevent the overlap of the float right span with text using CSS

I'm currently using rickshaw and have a graph hover/annotation where a color swatch (defined with a <span>) is overlapping text within the same <div>. Check out my HTML code below: <div class="detail" style="left:250px"> <d ...

Error in JSON Format Detected in Google Chrome Extension

Struggling with formatting the manifest for a simple Chrome extension I'm developing. I've been bouncing back and forth between these two resources to try and nail down the correct syntax: https://www.sitepoint.com/create-chrome-extension-10-mi ...

Bootstrap causing issues with correct display of div element

I'm having trouble getting my divs to display on the same row. It seems like when I have 2 rows, the button is positioned correctly. However, with only one row, the button ends up on the second row. Here is the current layout: https://i.sstatic.net/L ...

What is the best way to display the Edit and Delete buttons in a single column?

Currently, I am encountering a small issue. I am trying to display Edit and Delete Buttons in the same column but unfortunately, I am unable to achieve that. Let me provide you with my code. var dataTable; $(document).ready(function () { dataTa ...

How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this: <script> var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998'; //auto-generated var myValues = ...

Conceal the ancestor if the descendant four generations down is vacant

Hey there, I've been working with Beaver Builder on a website and integrating ACF to include a video module. However, not every page will necessarily have a video, and when it's not added, the div.fl-row still appears. I tried using a function to ...

Submitting a form with JQuery and Ajax technology

I am encountering an issue where I need to submit a form within Ajax and I keep getting a 'form.submit is not a function' error in jQuery. $("#form").validate({ // Define validation rules rules: { type: "required", group ...

Mix up the colors randomly

After searching extensively, I have been unable to find exactly what I am looking for. The closest matches only cover a portion of my needs which include: I am seeking a randomly selected color scheme that I have created but not yet implemented in code. T ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

Ensure that the tooltip remains visible within the confines of the page

In my Angular application, I have successfully implemented a versatile tooltip feature that goes beyond just displaying text. The tooltip is a div element that has the ability to contain various contents: .tooltip-master { position: relative; .tooltip ...

The props are not receiving the margin property

I am working on a styled component that needs to receive a prop to determine if it should have a margin on the left or right. It seems that there is a syntax issue that I am struggling with. Here is the code snippet: const FormDiv = styled.div` displa ...

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

What is the optimal frequency for saving data when dealing with a particularly extensive form?

I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

Leverage Bootstrap 4 for achieving flexible layouts and centering content with two elements using flex and justify-content

By using the d-flex, justify-content-center, and flex-grow-1 classes, I was able to achieve my desired layout with just 3 divs. <div class="row bg-primary d-flex justify-content-center"> <div class="col-auto"> LEFT </div> < ...

Capture all parameters in the URL, regardless of their names

Hello, I am currently utilizing the s:url tag to create a URL in my JSP file for pagination purposes. The issue I am facing is that when clicking on the previous link, it generates a URL in the address bar like someAction?previuos=prev. Similarly, when cli ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

There seems to be an issue with the loading of the JSON file

I have created a JSON representation that I would like to visualize using D3JS as a treemap. Following this tutorial: https://bl.ocks.org/d3indepth/d4f8938a1fd0914b41ea7cb4e2480ca8 The JSON I generated from the data is displaying correctly in the treemap ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...

Exploring the world of Leaflet. Have you ever encountered situations where adding a variable name to the GeoJSON file is crucial

Currently, I am in the process of learning Leaflet, JavaScript, and more. To test my understanding, I am using code examples from the Leaflet website and making modifications for my own purposes. However, I have noticed that in all the examples I have co ...