Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

behnampmdg3's avatar

Drag and drop between 2 divs with JQuery's draggable

Hello;

I need some help finishing this code.

I want to be able to drag and drop divs between other divs in the container.

Since the divs are built in a loop, it wouldn't be that hard to do I guess.

It's basically like this:

<div id='page_items' class="droppable">

    <div class= "main_block (and a bunch of classes)">Content 1</div>
    <div class= "main_block (and a bunch of classes)">Content 2</div>
    ***DRAG HERE***
    <div class= "main_block (and a bunch of classes)">Content 3</div>
    <div class= "main_block (and a bunch of classes)">Content 4</div>
    <div class= "main_block (and a bunch of classes)">Content 4</div>
    ***DRAG HERE, OR HERE ETC ***
    <div class= "main_block (and a bunch of classes)">Content 4</div>
    <div class= "main_block (and a bunch of classes)">Content 4</div>

</div>

I made a demo page so you see it.

The red div is the draggable and #page_items which is the parent, is the dropable.

https://webmoosh.com/edit-template/1/112

I am not sure but I think I have to somehow find the closest divs with the class .main_block and do something like

$("<div class=\"main_block row text-center ui-sortable-handle ui-sortable-helper\" ><div class=\"<?php // echo $page_width_class;?> page_blocks\" style=''><div class=\"box\" style = \" background-color:#cccccc; border:4px dashed #ffffff;\">Some things</div></div></div>" ).insertBefore( ".main_block" );

But I am still far from the results.

Also, have some Z-index issues as you can see. Stack didn't work!

Tips and help with the solution would be appreciated.

Thanks

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

It would be better if your code was on codepen or something that is editable and we can see/edit the actual code, but what you are asking for is in the docs. See this example: https://jqueryui.com/draggable/#sortable

  $( function() {
    // handle the sortable
    $( "#sortable" ).sortable({
      revert: true
    });

    // connect the draggable item to the sortable
    $( "#draggable" ).draggable({
      connectToSortable: "#sortable",
      helper: "clone",
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  } );
1 like
ohffs's avatar

If you're not 100% tied to the jquery - the draggable library from shopify is really easy to use. There's also dragula which is also pretty straightforward. Might be worth a quick look :-)

Please or to participate in this conversation.