function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NewBie09NewBie09 

Lightning drag and drop using jquery

Hello,
I want to create a lightning component to drag and drop fields from one div to another, can anyone help me with this :) 
NagendraNagendra (Salesforce Developers) 
Hi Dinesh,

Please find the sample code below which will point you in the right direction.

Component Code:
<aura:component implements="force:appHostable">
    <aura:attribute name="startId" type="string"/>
    <aura:attribute name="parentId" type="string"/>

    <div class="div1" id="div1" ondrop="{!c.drop}" ondragover="{!c.allowDrop}">
        <img src="{!$Resource.Pic1}" draggable="true" ondragstart="{!c.drag}" id="drag1" width="88" height="31"/>
    </div>

    <div class="div2" id="div2" ondrop="{!c.drop}" ondragover="{!c.allowDrop}">
        <img src="{!$Resource.Pic2}" draggable="true" ondragstart="{!c.drag}" id="drag2" width="88" height="31"/>
    </div>
    <input type="button" onclick="{!c.MoveDiv}" value="Click Me" />
    <div class="div2" id="div3" ondrop="{!c.drop}" ondragover="{!c.allowDrop}"><span id="drag3"> </span></div>

</aura:component>
Controller Code:
({
    allowDrop: function(cmp, event, helper){
        event.preventDefault();
    },
    drag: function(cmp, ev, helper){
          var parentId = document.getElementById(ev.target.id).parentElement.id;
        cmp.set("v.startId",ev.target.id);
        cmp.set("v.parentId",parentId);
    },
    drop: function(cmp, ev, helper){
        var drag = cmp.get("v.startId");
        var div = ev.target.id;
        var fragment = document.createDocumentFragment();
        fragment.appendChild(document.getElementById(drag));
        document.getElementById(div).appendChild(fragment);
        var c = document.getElementById(div).children;
        var x = document.getElementById('drag1').parentElement.id;
        var fragment = document.createDocumentFragment();
        fragment.appendChild(document.getElementById(c[0].id));
        document.getElementById(cmp.get("v.parentId")).appendChild(fragment);
    }
})
Style Code:
.THIS.div1 {
    float: left;
    width: 100px;
    height: 35px;
    margin: 10px;
    padding: 10px;
    border: 1px solid black;
}
.THIS.div2 {
    float: left;
    width: 300px;
    height: 100px;
    margin: 20px;
    padding: 10px;
    border: 1px solid black;
}
Hope this helps.

Please mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks,
Nagendra


 
NewBie09NewBie09
@Nagendra Actually the above code sometimes replaces (swaps) the data from the target div OR sometimes data is moved to the target div.