Can I use HTML5 drag and drop in dynamically generated elements?

Edit: I know this seems like a duplicate question, but it is very specific to HTML5 drag and drop events. I have no problem adding in jQuery events just the HTML5 drag and drop function.

I used basic jQuery several times to add drag and drop functionality to the page, but I would like to use the new HTML5 drag and drop feature for my current project. Drag works fine for any element that I include in HTML, but it seems like I cannot dynamically add elements and drag and drop them. I suspect this is because all draggable event listeners are linked when the page loads before my new items are created. Is anyone lucky using HTML5 so that dynamically added elements are draggable? Or is there a way to relink event listeners without reloading the page?

Using .bind() with any of the HTML5 drag and drop events does not work. those.

 $(newElement).bind('drag', function(e){ console.log('do you even drag, bro?'); }); 

will never fire, although .bind() with the click event works fine. I assume this is because drag means nothing to jQuery. By the way, I am adding the draggable="true" HTML tag to the new element.

So who has success stories for linking HTML5 drag and drop events to dynamically created elements, or is this not possible? Thank you

+6
source share
1 answer

There are two ways to do this. The first is to use some kind of ancestor element that will exist during the call to bind ():

 $('.someParent').on('drag', '.newElement', function(){ console.log('do you even drag, bro?'); }); 

Secondly, structure your code so that your binding function is called after creating your new element:

 var $newElement = $('<div class="newElement"></div>'); $newElement.on('drag', function(e){ console.log('do you even drag, bro?'); }); 
+7
source

Source: https://habr.com/ru/post/978302/


All Articles