Search code examples
javascripthtmljquerylayout

Append table with position is not exactly showing where it was


I am developing a website with Jquery-ui draggables. In the parent div block "container" there are many child draggables which allows user to freely move around the div block.

    <div class="container">
      <div class="draggable ui-widget-content" id="1">Table 1</div>
      <div class="draggable ui-widget-content" id="1">Table 2</div>
      ...
    </div>

I implemented a save function which saves the position of each div block as a json string. It stores the position of the draggables and their IDs. So it can be loaded with where they were at last time.

[{"id":"1","left":"256","top":"226"},{"id":"2","left":"256","top":"632"},{"id":"3","left":"1330","top":"226"},{"id":"4","left":"1330","top":"632"},{"id":"5","left":"818","top":"417"}]

Here's the problem:

I loaded the data from json. It turns out all the position is all wrong.

I recreated using JSFiddle to address the issue: https://jsfiddle.net/braveminds1823/wcmxL2bj/3/

Before saving Before saving

After saving, loading the position from json Loading the position from json

Edit: I know setting the position to absolute works, but since my website is responsive. The draggables will break out from the container and cover up the web content


Solution

  • You can see from what you've provided in the question (not just the fiddle) that your stored values are not correct.

    Looking at just "table" - when you load, it's 20x20, but when you move it further left and up, it's now 256x226 - so clearly not saving correctly.

    Your issue is with your use of position

    From MDN position:

    relative

    The element is positioned according to the normal flow of the document,
    and then offset relative to itself

    so the inside squares do not want position:relative, they want position:absolute

    absolute

    The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor

    So two small changes, in the css:

    .draggable {
       position:absolute;
    }
    #containment-wrapper {
       position:relative;
    }
    

    so that the draggable items are positioned absolutely, relative to the parent wrapper.

    Otherwise, your code works fine.

    Updated fiddle: https://jsfiddle.net/hrfx9sky/1/