Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Drag and Drop dataTransfer and Chrome

The following code:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script>
function allowDrop(ev)
{
console.log(ev.dataTransfer.getData("Text"));
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>
</head>
<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

with Firefox get correctly the dataTransfer object and returns the image's id (drag1) when the allowDrop function called by ondragover event is executed, but in Chrome getData returns an empty string. Is it a bug or Chrome returns a valid dataTransfer object only with the ondrop event?

like image 359
xdevel2000 Avatar asked Oct 18 '12 15:10

xdevel2000


People also ask

Is drag and drop possible using HTML5?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

What is the correct way to set the dragged data in HTML5?

setData() The DataTransfer. setData() method sets the drag operation's drag data to the specified data and type. If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type.

How will you make an image draggable in HTML5?

To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page.


1 Answers

Chrome doesn't set the dataTransfer before drop. I just set my drag reference in a "global" variable instead. :-)

like image 145
Per Digre Avatar answered Nov 01 '22 16:11

Per Digre