Aetherus
Aetherus

Reputation: 8888

How to remove ghost image when dragging an img using CSS or JavaScript?

Problem

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.

Trial and error #1

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.

Trial and error #2

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.

Trial and error #3

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).

Trial and error #4

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

Answers (1)

Aetherus
Aetherus

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

Related Questions