Duncan Duncan - 11 months ago 81
Javascript Question

HTML5 setDragImage(): dragIcon.width does absolutely nothing

When using the HTML5 drag and drop API, it would appears though the

property on has no impact on the width of an image being used as an icon for dragging. Take this fiddle for example: http://jsfiddle.net/cnAHv/7/. You can set
to anything you want, and it will not change the actual width of the icon.

Most of the resources on the web seem to arbitrarily set
to 100. Is this just a matter of people copying eachother's code without checking functionality?


  1. Is the width property on an image variable actually something that setDragImage() will accept?

  2. If not, how would you set the width of the icon without manually changing sizing the image in a program like photoshop?

Answer Source

When you use an <img> in setDragImage Javascript will just use the actual image bitmap data, ignoring other attributes like width. Check the specs.

However if you do something like this:

function handleDragStart(e) {
    var dragIcon = document.createElement('img');
    dragIcon.src = 'http://jsfiddle.net/favicon.png';
    dragIcon.width = '100';
    var div = document.createElement('div');
    e.dataTransfer.setDragImage(div, -10, -10);


You will see the drag shadow now contains the bigger image. It occurs because when we use other visible HTML elements (that's why I appended the DIV to the body), the browser will use its rendered view as a drag image.