EasterBunnyBugSmasher
EasterBunnyBugSmasher

Reputation: 1582

adding event listener dynamically

I'm trying to do add an event listener to a dynamically created object

var teamDiv = document.createElement("div");

obviously, following doesn't work:

teamDiv.onDragStart="drag(event)";

so I tried this:

teamDiv.addEventListener("dragstart",function(event){drag(event);});

and

var dragFunction = new Function("event","drag(event);");
teamDiv.addEventListener("dragstart", dragFunction);

and

teamDiv.addEventListener("dragstart", function(teamDiv) {dragObj(teamDiv);});

but nothing works. Can anyone help me with this?

thanks in advance,

Dirk

Upvotes: 0

Views: 933

Answers (1)

Ingo Bürk
Ingo Bürk

Reputation: 20033

Did you remember to a) append the element and b) make it draggable? See this:

var teamDiv = document.createElement('div');

// make it draggable
teamDiv.draggable = 'true';

// append it
document.body.appendChild(teamDiv);

function drag(event) {
    alert("You dragged me");
}

// either one of those will work
// teamDiv.addEventListener("dragstart", drag);
// teamDiv.ondragstart = drag;

Fiddle: http://jsfiddle.net/ZfXa5/1/

Events aren't camel-cased, so onDragStart won't work, it has to be ondragstart. You should also really avoid putting executable code into strings. They will be eval-ed, which is just completely unnecessary. eval is evil.

Upvotes: 4

Related Questions