0

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

1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I think it already worked from start. My problem was... I expected to see the ondragstart attribute in the div tag when inspecting it with the Firefox Inspector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.