I’m trying to implement a drag n drop interface to build out list of ‘Products’.
Each ‘Product’ has the following HTML:
<div class="pcontainer" data-id="1" draggable="true" ondragstart="drag(event)">
<p class="productname">...</p>
<img class="productimage" href="..."/>
</div>
I want to allow users to add the product to a ‘wishlist’ by dragging from anywhere inside the productcontainer div the product and drop it on a target.
The drop target is as follows:
<div id="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">
Drop Products Here
</div>
I’m implemented a prototype using simple HTML5, and it seems to work well, except that if I click directly on any of the elements inside the div, it doesn’t drag correctly.
Javascript:
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
//get the product id (with jquery)
var $target = $(ev.target);
var id = $target.attr('data-id');
ev.dataTransfer.setData("ID",id);
}
function drop(ev)
{
ev.preventDefault();
var id=ev.dataTransfer.getData("ID");
//do stuff to save product to list using its id
...
}
I modified this code from this simple demo at w3schools. Is there a simple way to make all drags on the inner elements translate to drags on the container element?
Or is there all-together better approach to doing this? (browser compatibility is a big issue with this html5 approach). I’m aware that a jQuery draggable library exists but I’m not sure if it is what I really need.
UPDATE:
Created JSFiddle so you can see what I mean in action:
JsFiddle Example
If you drag from the padding then it alerts 1, if you drag from the image it alerts undefined
Sooo yea… The jquery-ui draggable and droppable were exactly what I needed. See these demos