I need to dynamically create two DIVs and an item to drag/drop between the two. If I code static HTML this works fine but dynamically I am missing something. Has someone been able to define drag events dynamically and have them work?

<html>
<head>
<script>
    function main() {

        //SOURCE    
        var source = document.createElement("DIV");
        source.id="source";
        source.innerHTML='<h1 class=title>SOURCE</h1>';
        document.body.appendChild(source);

        //ITEM      
        var item=document.createElement("DIV");
        item.id="item";
        item.draggable="true";
        item.ondragstart="function(){ alert('drag'); }";
        item.innerHTML='DRAG ME';
        source.appendChild(item);

        //TARGET
        var target = document.createElement("DIV");
        target.id="target";
        target.innerHTML="<h1 class=title>TARGET</h1>";
        target.ondragover="function(){ alert('DragOver'); }";
        target.ondrop="function(){ alert('Drop'); }";
        document.body.appendChild(target);

    }
</script>
<style>div   {border-style: solid;border-width: 3px;padding: 10px;margin: 10px;width:80%;}</style>
</head>
<body  onload=main()>
</body>
</html>

Recommended Answers

All 3 Replies

Member Avatar for stbuchok

Try removing the quotes from the events. For example:

target.ondragover="function(){ alert('DragOver'); }";

would become

target.ondragover=function(){ alert('DragOver'); };

Argh, so simple but I could not see it - thank you. The only problem now is the target does not allow drop... I'm searching but if you have an idea I would appreciate it! I cannot get the drop function to fire...

        target.ondrop=function(){ alert('Drop'); };

Basically you need to get the events and use them.
To allow drop you need to evt.preventDefault() on dragOver and also to stop browser redirection on dropped.

Checkout an working demo that i made based on your code: https://jsfiddle.net/alemonteiro/vsd3cdwj/6/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.