elidrinkstea
elidrinkstea

Reputation: 33

Add events dynamically to a div

So I have the following div:

<div id="mylist">

Inside this div, I have another div I want to dynamically create:

<div id="object3" class="objects" 
  draggable="true"
  ondragstart="drag_start(event)" 
  ondragend="drag_end(event)">
  BWA
</div>

Right now I wrote a function:

function myFunction() {
  var node = document.createElement("div");
  node.className="objects";
  node.draggable= "true";
  var textnode = document.createTextNode("BWA");
  node.appendChild(textnode);
  document.getElementById("mylist").appendChild(node);
}

How could I append ondragstart="drag_start(event)" and ondragend=drag_end(event)" dynamically to the div I create?

Thanks!

Upvotes: 2

Views: 52

Answers (1)

Dave Anderson
Dave Anderson

Reputation: 12294

You will need to use addEventListener().

node.addEventListener("dragstart", drag_start, false);
node.addEventListener("dragend", drag_end, false);

This assumes the drag_start and drag_end functions are declared in the correct scope and that the events will be fired by your element.

Upvotes: 3

Related Questions