Reputation: 8888
I have the following html snippet
<div class="image-wrapper">
<img src="...">
</div>
I want to change the position of the .image-wrapper
when a user drags the image, but I don't want the ghost image while dragging the image.
I've tried adding draggable="false"
to the image, like
<div class="image-wrapper">
<img src="..." draggable="false">
</div>
but this totally prevents the image to be able to drag, and thus no event is triggered when I try to drag the image. I do want to drag the image, I just don't want the ghost image when dragging.
I've tried the following CSS
img {
-webkit-user-drag: none;
user-drag: none;
}
but again my image becomes undraggable. By the way, any value other than none
won't remove the ghost image.
I've tried the JS approach (with jQuery)
$('img').on('dragstart', function (event) {
var emptyImage = document.createElement('img');
// Set the src to be a 0x0 gif
emptyImage.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
event.dataTransfer.setDragImage(emptyImage, 0, 0);
});
but my chromium browser complains that event.dataTransfer
is undefined
(I've double checked the code and there is no typo).
I've tried
$('img').on('dragstart', function (event) {
event.preventDefault();
});
but it seems that the event stops propagation and thus the wrapping div can't catch the event and change its position accordingly.
So how can I enable image dragging, keeping the event properly propagated, and remove the ghost image while dragging?
Thanks in advance.
Upvotes: 1
Views: 3038
Reputation: 8888
Since @Kaiido don't want to answer the question, I'll answer this question myself using his advice.
As @Kaiido pointed out in the comments of the question, jQuery wraps the dom events. The original event is available through event.originalEvent
. So I can just modify my "Trial and error #3" like
$('img').on('dragstart', function (event) {
var emptyImage = document.createElement('img');
// Set the src to be a 0x0 gif
emptyImage.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
event.originalEvent.dataTransfer.setDragImage(emptyImage, 0, 0);
});
Upvotes: 2