Search code examples
javascriptdrag-and-drop

How to add ondragstart=“drag(event)” to a dynamically created elements (li)?


Examples:

list tag created dynamically:

var newli = document.createElement('li');
newli.id = "fstId";

How do you give this list tag the property " ondragstart="drag(event)" "?

please advise me...

Thank you.


Solution

  • Drag & Drop are event that are passed down to any DOM elements. While creating a element dynamically you first have to enable its draggable property & add event for drag & other events flowed by in Drag & Drop you can find it in details below

    1. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

    Further you can add those event & flag like this given below,

    var node = document.createElement("li"); 
    node.draggable = true;
    node.addEventListener('drag', setDragging); 
    

    Here setDraging is a callback function on which you have to describe what to do when dragging. You can find the complete implementation below here but its better to go first to previous link I described above. Here is the full implementation,

    1. https://medium.com/better-programming/create-a-sortable-list-with-draggable-items-using-javascript-9ef38f96b258