0

I know there has been numerous similiar questions on stackoverflow, I've read several of them, but none provided there answers worked in my case. I want to change cursor while dragging HTML element. I tried this:

var startX = null;
var startY = null;
var element = document.getElementById('bla');

element.addEventListener('dragstart', onDragStart, true);
element.addEventListener('dragend', onDragEnd, true);
element.addEventListener('drag', onDrag, true);

function onDragStart(e){

  startX = e.screenX;
  startY = e.screenY;
  e.target.style.cursor = "move";
}

function onDrag(e){

    e.target.style.cursor = "move";
}

function onDragEnd(e){

    var style = document.defaultView.getComputedStyle(element);

  var newLeft = parseInt(style.left) + e.screenX - startX;
  var newTop = parseInt(style.top) + e.screenY - startY;

  e.target.style.left = newLeft + 'px';
  e.target.style.top = newTop + 'px';

  e.target.style.cursor = "default";
}

But it doesn't work. I have no idea why on earth e.target.style.cursor = "move" doesn't work. I tried changing it to document.body.style.cursor = "move", but it doesn't work either. Any help with solving this problem with explanation why my code doesn't work will be greatly appreciated.

JS Fiddle link: https://jsfiddle.net/4w20xxvp/59/

Ps. I'm looking for pure JS solution, no JQuery. Ps2. I couldn't get answers from to work in my case. And I don't want to use custom cursor images, just standard css ones.

Furman
  • 2,017
  • 3
  • 25
  • 43
  • Possible duplicate of [HTML5 Drag & Drop Change icon/cursor while dragging](https://stackoverflow.com/questions/10119514/html5-drag-drop-change-icon-cursor-while-dragging) – Nisarg Shah Aug 10 '17 at 08:42
  • I couldn't use answers in above link to work in my case. And I don't want to use custom image (as explained in one of answers), I want to use one of css cursors (style.cursor). – Furman Aug 10 '17 at 08:54
  • Which os/browser do you use? My mac/chrome works fine with your code. – Sereja Nagin Dec 03 '17 at 03:49

1 Answers1

-2

Try to preventDefault on the other drag events. Also, you might want to consider adding a drop target that would handle dragover events.

document.addEventListener('dragover', (e) => e.preventDefault(), true)

(Fiddle)

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Saeed A
  • 1
  • 1