0

I'm trying to make elements in a list draggable but I'm running into an issue that I can't figure out. My code below follows a general format I've seen in some tutorials.

My list of draggable elements is formatted as such:

function startDrag(e) {
    e.dataTransfer.effectAllowed = 'move';
    console.debug(e);
    e.dataTransfer.setDragImage(e.target, 0, 0);
    return true;
}
<ul>
<li class="drag" draggable="true" ondragstart="startDrag(e)"><img src="/my/image/path.svg"></li>
<li class="drag" draggable="true" ondragstart="startDrag(e)"><img src="/my/image/path2.svg"></li>
</ul>

I'm just trying to get the startDrag function to fire but I keep getting:

Uncaught ReferenceError: e is not defined

This is reproduce-able in my snippet above.

What am I missing here? Thank you!

Vecta
  • 2,312
  • 5
  • 28
  • 47

1 Answers1

0

Inline event handling attributes are not passed a reference to a DOM event and that's why your argument is undefined.

Don't use inline HTML event attributes to hook up events. That's a 25+ year old technique that just will not die.

Follow modern standards and use .addEventListener() which will automatically be passed a reference to the DOM event that triggered the handler.

document.querySelectorAll(".drag").forEach(function(item){
  item.addEventListener("dragstart", startDrag);
});

function startDrag(e) {
    console.log("Drag started! Event was: ", e.type);
}
<ul>
  <li class="drag" draggable="true">Drag me.</li>
  <li class="drag" draggable="true">No, drag me!</li>
</ul>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71