wallabe
wallabe

Reputation: 53

Issues dragging elements in Firefox

Are there any reasons why an image would not be draggable in Firefox even when the attribute draggable="true"? I'm designing an image swapping script in JS but am having some problems when running it in Firefox. While the code works fine in Chrome, Edge, and IE, when I try and drag and drop an image in Firefox it doesn't appear as if the browser is letting me drag the image (no ghost image appears) and thus my drag event isn't firing or triggering any of the drop events. I am generating the image via document.createElement('img') and setting the attributes with

imgElement.setAttribute('draggable', true);
imgElement.setAttribute('ondragstart', 'drag(event)');

my drag function:

function drag(ev) {
 if (!ev.target.classList.contains(clickClass)) {
  return;
 }

 ev.dataTransfer.setData("text", ev.target.id);
 document.getElementById(ev.target.id).parentElement.setAttribute('class', 'noclick');
};

I read in a different question that the drag event may not fire in Firefox if data isn't being transferred, however, that doesn't seem to be the issue here.

Upvotes: 0

Views: 1471

Answers (2)

Mike
Mike

Reputation: 1

It seems in Firefox, at least in v61, setting the draggable attribute to false, instead of true will give you the desired result - allowing the image to drag along with the movement of the mouse.

element.setAttribute('draggable', false);

It may be that Firefox assumes it will handle the dragging of images, unless you explictly set an attribute to false, in which case you use your own js handler to move the image yourself.

It also seems Firefox resets the attribute back to true by default once the initial movement has occurred and the mouse button released. The draggable attribute must be reset back to false to start the process all over again. But, that shouldn't be a problem considering you're likely handling all mouse events for that image, and can easily insert a line of code to ensure that dragging is false when you need it to be.

Upvotes: 0

Dekel
Dekel

Reputation: 62556

Instead of imgElement.setAttribute('ondragstart', 'drag(event)'); you should add the dragstart listener instead:

imgElement.addEventListener('dragstart', function(e){
    drag(e);
});

Upvotes: 2

Related Questions