thnkwthprtls
thnkwthprtls

Reputation: 3487

addEventListener not working for onDragStart

In my Javascript, I have the following code:

var a = document.createElement("a");  //Needs to be a, not div
a.draggable = true;
a.addEventListener("dragstart", function(event){drag(event)});
$("#id_of_main_page_in_html").append(a);

function drag(ev){debugger;}

When I run this code and attempt to drag this object, it should trigger the debugger, but nothing happens. I tried to run the same code using "click" instead of "dragstart" and it worked, that is when I clicked the object it triggered the function with the debugger, but dragstart won't work. Is there something I am doing incorrectly?

Upvotes: 1

Views: 1840

Answers (2)

Just use:

a.ondragstart = drag;

https://www.w3schools.com/jsref/event_ondragstart.asp

Upvotes: 0

thnkwthprtls
thnkwthprtls

Reputation: 3487

So as usual, I finally get it working immediately after asking SO for help... I found that adding the line a.href = "#"; before the addEventListener call fixed it.

Upvotes: 1

Related Questions