The image in drag and drop ghost preview is not appearing on Firefox

I want to show a ghost element instead of the default browser preview while dragging and dropping. However, in Firefox, the image inside the ghost element is not displayed during dragging. Oddly enough, if I drop it and then drag again, the image does appear.

It seems like this could be a cache-related issue, but I'm unsure how to pre-cache the image in this scenario.

Here's the code snippet:

//html:

<div class="parent container">
<img class="element" src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg" draggable="true" />
</div>

//js:

document.querySelector(".element").addEventListener("dragstart", function(e) {
    var img = document.createElement("img");
    var div = document.createElement('div');
    div.style.width = '100px';
    div.style.height = '100px';
    div.style.position = 'fixed';
    div.style.top = '-1000000px';
    div.style.left = '-1000000px';
    div.style.border = '2px solid red';

    img.src = "http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg";
    img.style.width = '100px';
    img.style.height = '100px';
    div.appendChild(img);
    document.body.appendChild(div);
    e.dataTransfer.setData('text/plain', 'test');
    e.dataTransfer.setDragImage(div, 0, 0);
}, false);

Fiddle: https://jsfiddle.net/etseq5cg/5/

Follow these steps to recreate the issue:

1) Open the fiddle or run the snippet

2) Try to drag the sample image

Actual: You will only see an empty square with red border

Expected: You should see a square with the image inside

To reproduce the issue, you may need to force-reload the page (Ctrl+F5). This suggests that the problem might be related to caching.

Note: Removing the ghost element from the DOM in the dragend handler is not relevant to this case.

Update:

1) The real use-case involves a view with a large number of images (~500), so pre-caching images with JS is not a viable solution.

2) For those who couldn't replicate the issue, here's a screenshot: the initial preview after a hard reload (Ctrl+F5) and then the second drag attempt. It's worth noting that no HTTP requests are shown in the network tab of the web inspector in either case. https://i.stack.imgur.com/tAgRW.png

Answer №1

When testing your jsfiddle in Firefox 53 on Windows 7, I didn't encounter any issues with the ghost image and dragged image having the same URL. However, a problem arises when using a ghost image with a different URL.

To preload the ghost image, you can add a hidden img element like this:

<div class="container">
    <img class="element" draggable="true" src="http://the.element.image" />
    <img class="hiddenGhost" src="http://the.ghost.image" />
</div>

In my tests, I found that hiding the image using visibility: hidden worked better than other techniques such as display: none, null size, or moving it out of the viewport.

You can experiment with this method using two draggable images in this updated jsfiddle. Remember to adjust the ghost image names (e.g. 225x225) to ensure no caching issues.

If preloading the image is not an option for you, consider checking this resource for troubleshooting tips. Additionally, forcing a repaint after adding the div control to the body in the dragstart event handler might help. You can achieve this by calling div.offsetHeight:

div.appendChild(img);
document.body.appendChild(div);
div.offsetHeight; // Trigger repaint

Answer №2

When using CSS, apply the pseudo-class :hover to the .parent element and set the background of the .element element to url("/path/to/image") when hovered over. This will fetch the image at hover for the parent element. Additionally, during the dragstart event, set the className of the div to "element".

.element {
  width: 100px;
  height: 100px;
  background: url("http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg");
  background-size: 100px 100px;
  
}

.parent:hover {
  background: url("http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg");
  background-size: 0px 0px;
}
<div class="parent container">

  <img class="element" src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg" draggable="true" />

</div>
    <script>
    function handleImage(e) {
      var div = document.createElement('div');
      div.style.width = '100px';
      div.style.height = '100px';
      div.style.position = 'fixed';
      div.style.top = '-1000000px';
      div.style.left = '-1000000px';
      div.style.border = '2px solid red';
      div.className = "element";
      document.body.appendChild(div);
      e.dataTransfer.setData('text/plain', 'test');
      e.dataTransfer.setDragImage(div, 0, 0);
    }
 document.querySelector(".element")
 .addEventListener("dragstart", handleImage, false);
  </script>

Check out the code on jsfiddle here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code snippet: <div class=" ...

Struggling to eliminate the unseen padding or white space preventing the text from wrapping under the button

Just starting out with html and css and could use some assistance with a small issue I've come across. While redesigning a website, I have a three-button form (Donate, Find, Subscribe). I'm trying to get the paragraph underneath the Donate and Fi ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...

Tips for adjusting the width of Material UI TextField within a Table

I am utilizing a Material UI Table. This is how I construct it: tableValues.map((curRow, row) => { tableRows.push( <TableRow key={this.state.key + "_row_" + row}> {curRow.map((cellContent, col) => { let adHocProps ...

"Clicking on the 'View More' button within a foreach loop is only functional for the

I am trying to iterate through a list of items using a foreach loop, and each item has a "view more" option. The intention is that when I click on this option, it should expand to show more details about the respective item. However, I am encountering an i ...

Customize WordPress pages by adding a variety of unique logos for a

I am currently customizing a WordPress theme (Increate themes) for a client. They are looking to have a page with different content and a unique logo. My question is, how can I change the logo specifically for this page? This is the section of code in my ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

Determine the currently active view on a mobile device

I am trying to determine whether the user is viewing the website vertically or horizontally on their mobile device or iPad in order to adjust the image scale accordingly. For example: If the user is viewing the page horizontally, I want the image style t ...

Tips for implementing an HTML modal with AngularJS binding for a pop up effect

As a beginner in AngularJS, I am facing a challenge. I have an HTML page that I want to display as a pop-up in another HTML page (both pages have content loaded from controllers). Using the router works fine for moving between pages, but now I want the s ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

"Compilation error: 'not defined' is not recognized, 'no-undef

I am currently working on a login form that will fetch values from this API: However, the password field is currently empty, allowing any password to be accepted. This results in the error: Failed to compile 'userName' is not defined no-undef; ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

Styling the large drop-down menu for Internet Explorer 7

Check out the code snippet at http://jsfiddle.net/jN5G4/1/ Is there a way to align the drop-down menu for "5 Columns" to match the alignment of the other drop-downs? After removing the <a href...> </a> tags from the 5 Columns list item, the d ...

The issue where all buttons in a list are displaying the same ID

I am facing an issue with a row of buttons, all having the same class add-btn. Whenever I click on one button, I intend to log the id of its containing span. However, currently, all buttons are logging the span id of the first add-btn in the list. $(&apos ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the HTM ...