How to change DnD's (drag and drop) icon during dragover or dragenter? Is it even possible?
I am able to change the icon during dragstart if the source of the drop is inside the html page (for example drag a div in an other div). Here is my code, I am working with angular, I have set a plunker.
app.directive('drag', function() {
return {
link: function(scope, element, attr) {
element.attr('draggable', true);
element.css('cursor', 'move');
element.bind('dragstart', function(event) {
console.log('dragstart');
console.log(event.dataTransfer);
event.dataTransfer.effectAllowed = 'move';
var img = document.createElement("img");
img.src = "https://image.flaticon.com/teams/slug/google.jpg";
event.dataTransfer.setDragImage(img, 0, 0);
});
}
};
});
But it doesn't work to change the icon if the source is a file for example or an url, here is the code. I am trying to change the icon during dragover or dragenter.
element.bind('dragenter', function(event) {
console.log('dragenter');
event.dataTransfer.effectAllowed = 'move';
var img = document.createElement("img");
img.src = "https://image.flaticon.com/teams/slug/google.jpg";
event.dataTransfer.setDragImage(img, 0, 0);
});
element.bind('dragover', function(event) {
if (event.preventDefault) {
event.preventDefault();
}
if (event.stopPropagation) {
event.stopPropagation();
}
console.log('dragover');
element.addClass('dragged');
var img = document.createElement("img");
img.src = "https://image.flaticon.com/teams/slug/google.jpg";
event.dataTransfer.setDragImage(img, 0, 0);
return false;
});
As per the specification, you cannot use setDragImage on events other than drag start. See here: https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-setdragimage
The setDragImage(element, x, y) method must run the following steps:
If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.
If the drag data store's mode is not the read/write mode, return. Nothing happens.
If element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified).
Set the drag data store hot spot coordinate to the given x, y coordinate.
And here, you can see that the drag data store is in read/write mode only on dragstart: https://html.spec.whatwg.org/multipage/dnd.html#concept-dnd-rw
Read/write mode For the dragstart event. New data can be added to the drag data store.
These are modes are there for security reasons, there are things you can do on the different stages of a drag and drop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With