Reputation: 3279
I'm dynamically creating div elements using JavaScript, also there is a move icon in each div which user can use to drag/move div, here is my div creation code:
var _body = document.getElementsByTagName('body')[0];
var _div = document.createElement('div');
_div.style.width = "250px";
_div.style.height = "150px";
_div.style.position = "relative";
_div.id = "div" + count.toString();
var imgMove = document.createElement("img");
imgMove.setAttribute("src", "boxmove.png");
_div.appendChild(imgMove);
how can I use JQuery draggable() function to move my div when user drags move icon, any other solution?
Upvotes: 0
Views: 1711
Reputation: 31909
Here is quick solution for drag-and-drop:
<script type="text/javascript">
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev){
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
This is the HTML markup:
<style type="text/css">
[ondragover] {width:200px;height:200px; outline: 1px solid #ccc}
[draggable] {width:48px;height:48px;background-color:#999; border:1px solid #eaeaea;position:relative}
[draggable]:hover {cursor:pointer}
</style>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div2"ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="drag1" draggable="true" ondragstart="drag(event)"></div>
<div id="drag2" draggable="true" ondragstart="drag(event)"></div>
<div id="drag3" draggable="true" ondragstart="drag(event)"></div>
<div id="drag4" draggable="true" ondragstart="drag(event)"></div>
</div>
Upvotes: 1
Reputation: 64536
Set the handle
option to img
which will mean the image will be used as the drag handle.
_body.appendChild(_div);
$(_div).draggable({ handle: "img" });
The handle
option is a selector to target an element within the container, so you can be more specific by giving the image a class name, which would be needed if you had multiple images in the div, but only wanted a certain image as the drag handler.
From the docs
handle
If specified, restricts dragging from starting unless the mousedown occurs on the specified element(s). Only elements that descend from the draggable element are permitted.
Upvotes: 1