Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE

I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you.

My goal is to develop a scheduler application.

https://i.sstatic.net/8sdQS.jpg

The essential functionality I require includes the ability to vertically resize colored divs and drag them into any row or cell within the table.

For instance, being able to drag and resize an orange div to a row below it.

https://i.sstatic.net/8dpXe.jpg

Alternatively, when resizing the green div, the yellow div should automatically move to the row beneath it.

https://i.sstatic.net/WhTtQ.jpg

Dragging the divs should be straightforward.

I have a functional sandbox DEMO

I came across a fiddle online that perfectly matches my requirements, but it relies on Jquery which I prefer not to use if possible. FIDDLE OF WHAT I AM LOOKING FOR


document.getElementById('drop').addEventListener("click", () => {
  sortItemsByTable();
});
    
document.getElementById('resize').addEventListener("mouseover", () => {
  adjustSizeAndPosition();
});

Answer №1

JavaScript Solution

Your statement:

I found a solution online in a JS Fiddle that fits my requirements, but it relies on jQuery which I'd rather avoid if possible.

To mimic the functionality of the aforementioned JS Fiddle, I used plain JavaScript and the HTML Drag and Drop API. Here is my adaptation.

Note: To resize boxes vertically instead of horizontally, change resize: horizontal; to resize: vertical;.

Check out the code snippet below.

document.addEventListener('DOMContentLoaded', (event) => {
  var dragSrcEl = null;
  
  function handleDragStart(e) {
    dragSrcEl = this;

    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
  }

  // Additional functions omitted for brevity

});
table {
  height: 100px;
}

td {
  height: 68px;
  width: 150px;
  border: gray thin solid;
}

.resize {
// CSS properties here
}

td.drop {
// CSS properties here
}
<!DOCTYPE html>
<html lang='en'>

<head>
// Head content
</head>

<body>
  <div>
    <table cellspacing='3'>
      <tr>
        // Table rows and headers
      </tr>

      <tbody class='container'>
        <tr>
          // Table data with draggable elements
        </tr>

        <tr>
         // Additional table data rows
        </tr>
      </tbody>
    </table>
  </div>
</body>

</html>

Answer №2

Check out this awesome jQuery demonstration here. It's a sleek and sophisticated approach.

Enhancing HTML DOM elements with Draggable and Resizable Features using jQuery

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

ensure that angular's ng-if directive sets aside space to display content when triggered by an event

I'm facing an issue with my modal form setup where if a text-field is left blank, a label saying "it is required" is generated below the field, causing the "Proceed" button to move (along with all other elements below it). How can I make sure that DOM ...

JavaScript - Loading image from local file on Linux machine

I have a server running and serving an HTML page, but I am trying to display an image from a local drive on a Linux machine. I've tried using file://.., but it doesn't seem to be working for me on Ubuntu 18.04. There are no errors, the img tag ju ...

What could be causing the "No valid versions available for undefined" error to pop up during the installation of create-react-app?

Currently, I am in the process of installing React using the command prompt. Fortunately, NodeJS has already been successfully installed. However, upon executing the following command: npm i -g create-react-app An error message pops up displaying the fol ...

Finding a jQuery DOM element without using a loop

Can the element in variable d be identified directly instead of looping through each function? Take a look at the DOM below: <!DOCTYPE html> <html lang="en"> <head> <title></title> <script src="../jquery-ui ...

creating an animated loop within an Angular template

How can we display a dynamic loop in Angular template using an array of object data? [ { "name": "name", "text": "text", "replies": [{ "name": "Reply1", "t ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

Obtain the content from a dynamically generated dropdown menu and incorporate it into a separate file

My website features two dropdown menus - one for selecting countries and another for cities. The country menu is populated with data from a database, and once a country is selected, the city dropdown is dynamically filled with corresponding cities using a ...

What is the proper way to bind CoreUI's CSwitch component?

I am trying to incorporate the CSwitch component into a DevExtreme data grid. While the DxSwitch component functions correctly, I am unable to get the CSwitch to work properly. It seems like I might be using the wrong binding. Could that be the issue? < ...

Having trouble applying global styles in _app.js in NextJS?

After embarking on a new project, I diligently followed the guidelines outlined in this page from NextJS documentation: https://nextjs.org/docs/basic-features/built-in-css-support I meticulously copied every step provided under the section titled "Adding ...

The base64 code generated by the toDataURL method on the canvas appears to be incorrect

I am facing an issue with my code while using canvas to draw a cropped image with base 64. The problem is that it works perfectly on Chrome but gives me a blank image on Firefox. async function base64SquareCrop(imgbase64, size = 224) { const img = docume ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

The data-toggle function is not functioning properly with the code provided

Could someone shed some light on why my tabs and navigation bar dropdown button are not functioning properly? <div class="col-12"> <h2>Corporate Leadership</h2> <ul class = "nav nav-tabs&q ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Creating a div caption that mimics a form label, but with the background div border removed, can be achieved

Is there a way to create a div caption similar to a form label (positioned in the middle of the border), but without the div's border interfering? The issue is that I can't just use a background color for the H1 (caption) element because there is ...

Having trouble sending messages on the server?

Programmer Seeking Help with Adding Data on the Server using JavaScript Stack I am encountering an issue with my javascript code as I am attempting to use the post method to add data on the server-side, but it seems to not be posting successfully. Can ...

Issue encountered when assigning a new value to a private class property at a global scope in JavaScript

I am encountering an issue in my code where I define a private class member using "#", initialize it in the constructor, and then receive an error when attempting to set/access the value. Uncaught TypeError: Cannot read private member #mouse from an object ...

A method for retrieving the variables from the initial API function for use in a subsequent API function

$.getJSON(url, function (data) { $.getJSON(url_wind, function (data2) { //perform actions with 'data' and 'data2' }); }); While attempting to use the data from the initial getJSON() call in the second getJSON() call ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...