What are the steps to create a responsive drag and drop system with absolute positioning?

I'm currently working on a drag and drop web application using JQueryUI, but I'm facing an issue with responsiveness. I was wondering if anyone could provide some guidance or assistance?

Here is a snippet of my JavaScript code:


$(document).ready(function() {
  $(".draggable").draggable({
    helper: "clone",
    cursor: 'move'
  });
  $("#dropzone").droppable({
    drop: function (event, ui) {
      var canvas = $(this);
      if (!ui.draggable.hasClass('object')) {
        var canvasElement = ui.helper.clone();
        canvasElement.addClass('object');
        canvas.find("div").removeClass('activeElement');                
        canvasElement.addClass('activeElement');
        canvasElement.removeClass('draggable ui-draggable ui-draggable-handle ui-draggable-dragging');
        canvas.append(canvasElement);                

        canvasElement.css({
          left: (ui.position.left),
          top: (ui.position.top),
          position: 'absolute',
          zIndex: 10              
        });

        canvasElement.draggable({
          cursor: 'move',
          containment: '#dropzone'
        });
      }   
    } 
  });

I am currently employing absolute positioning in my design. How can I go about making this layout more responsive?

Answer №1

It seems like the issue you are experiencing is related to absolute positioning within an element that lacks relative positioning. Here's an example to illustrate:

<div style="position: relative; width: 200px; height: 200px; background: #ccc;">
  <div style="position: absolute; left: 75; top: 90; background: #fff;">Hello World</div>
</div>

When using absolute positioning inside a relative positioned element, the child will be placed relative to its parent. If the parent does not have relative positioning, the child will instead be positioned based on the document edges or the next parent with relative positioning.

To address this in your code, consider implementing something similar to the following example: https://jsfiddle.net/Twisty/zzv5gdg2/

HTML

<div id="content">
  <div id="element">
    <div class="draggable ui-widget-content">
      <p>Drag me</p>
    </div>
  </div>
  <div id="dropzone" class="ui-widget-header"></div>
</div>

CSS

.draggable {
  width: 90px;
  height: 90px;
  padding: 0.5em;
  float: left;
  margin: 10px 10px 10px 0;
}

#dropzone {
  width: 200px;
  height: 200px;
  padding: 0.5em;
  float: left;
  margin: 10px;
  position: relative
}

jQuery

$(function() {

  $(".draggable").draggable({
    helper: "clone",
    cursor: 'move'
  });

  $("#dropzone").droppable({
    drop: function(event, ui) {
      var canvas = $(this);
      if (!ui.draggable.hasClass('object')) {
        var canvasElement = ui.helper.clone();
        canvasElement.addClass('object');
        canvas.find("div").removeClass('activeElement');
        canvasElement.addClass('activeElement');
        canvasElement.removeClass('draggable ui-draggable ui-draggable-handle ui-draggable-dragging');
        canvas.append(canvasElement);

        var off = canvas.position();
        var canElOff = {
          left: ui.position.left - off.left,
          top: ui.position.top - off.top
        };

        canvasElement.css({
          left: canElOff.left,
          top: canElOff.top,
          position: 'absolute',
          zIndex: 10
        });

        canvasElement.draggable({
          cursor: 'move',
          containment: '#dropzone'
        });
      }
    }
  });
});

If there are still lingering questions about your goals or what "responsive" entails in this context, please update your post with more details for further assistance.

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

`vuetify sidebar with a nested menu``

I am trying to enhance the vuetify sidebar menu I created by adding a submenu to a specific title. Despite editing the code and data as shown below, I am unable to see any changes reflected. Below is the code snippet: <v-list flat class="mt- ...

Tips for linking real-time information to an array using AngularJS

Exploring Angular for the first time, I've embarked on creating a shopping cart web application. I came across a cart plugin online at https://www.codeproject.com/Articles/576246/A-Shopping-Cart-Application-Built-with-AngularJS, but it only supports s ...

Exploring the application of URL parameters in HTML code

How can I use URL parameters retrieved with Javascript in my HTML? <script> var url_string = window.location.href; //window.location.href var url = new URL(url_string); var c = url.searchParams.get("name"); console.log(c); </script> I am tryi ...

Load charts.js synchronously into a div using XMLHttpRequest

At the moment, there is a menu displayed on the left side of the page. When you click on the navigation links, the page content loads using the code snippet below: if (this.id == "view-charts") { $("#rightContainer").load("view-charts.php"); $(thi ...

Show the selection of form in a div using React

I am currently working on developing a user interface that dynamically updates based on the selection made by the client in a dropdown menu. The structure I have set up includes a React Parent component named App that renders two child components called In ...

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

What is the best way to use jQuery to toggle the hidden class on an inner div when a button inside a card is clicked?

How can I implement jQuery functionality to toggle the hidden class on an inner div by clicking a button inside a card? I attempted to create a container div containing multiple cards. The issue arises when I click the button - it only opens the panel, bu ...

What is the process for adjusting the color of a mat-divider?

Has anyone been successful in changing the color of mat-divider? I attempted the following but had no luck: component.html <mat-divider class="material-devider"></mat-divider> component.scss .material-devider { color: red } ...

Combining various font files under a single @font-face declaration

Here is the code snippet I'm currently working with: @font-face { font-family: 'icomoon'; src:url('../fonts/icons/icomoon.eot?2hq9os'); src:url('../fonts/icons/icomoon.eot?#iefix2hq9os') format('embedded-opent ...

The button must stay deactivated even if the page is refreshed

When I click on the submit button, it disables for 15 seconds before getting enabled again. However, if I refresh the page, the button becomes immediately enabled without waiting the disable time. Can someone please assist me with this issue? $(window). ...

jQuery unable to target Bootstrap button

I've been experiencing some trouble trying to attach a listener to a button I made with Bootstrap. <button type="button" id="buttonone" class="btn btn-default btn-lg good"> <span class="glyphicon glyphicon-minus" aria-hidden="true">< ...

Avoid using jQuery to invoke ASP.NET WebMethod

Despite checking various similar questions, I am still unable to find a solution to my problem. The issue is with my basic web page that contains the following code: <body> <form id="form1" runat="server"> <div id="Result"> ...

What is causing my CSS grid items to overlap instead of aligning neatly in rows and columns?

I am encountering an issue with CSS grid where items are stacking on top of each other when I assign them to grid template areas. As a newcomer to CSS grid, I suspect that I may be overlooking some key principles. You can view my playground here: https:// ...

Tips for choosing elements in jQuery that do not contain a particular element

How can I target elements in jQuery that do not contain a specific element within them? I am trying to create a sidebar that will close when the user clicks either the menu or the sidebar itself, excluding dropdown menus. Below is the structure of the menu ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

Use jQuery to replace this color with that color in CSS every time it appears

I have numerous div elements, some with a background-color: #aaa, others with font color: #aaa, and some with border-color: #aaa. There are also divs with various other colors. I am looking to update these colors (#aaa) to #ccc throughout the CSS. While ...

Add a specific CSS class to a div element depending on the status of a checkbox

Is there a way to dynamically append data based on the selected items in a checkbox table? I want to be able to add multiple or single items by clicking the add button. The key is to avoid appending duplicate data that already exists in the view. Any sugge ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

Resolve React Issue: Using Functions as React Children is Invalid

As I follow along with a React tutorial, I encountered an error while adding a POST request: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than ...

What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data: First Set: let training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ]; Second Set: let skill = [ "P1, Shooting", "P2, Passing", ]; I need to combine both arrays bas ...