Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the HTML5 drag-and-drop in dynamically created elements?

Edit: I know this looks like a duplicate question, but it's very specific to the HTML5 drag events. I'm not having a problem adding in jQuery events, just the HTML5 drag and drop functionality.

I've used basic jQuery several times to add drag-and-drop functionality to a page, but I'd like to use the new HTML5 drag-and-drop feature for my current project. Drag works great for any element I include in the HTML, but I don't seem to be able to add elements dynamically and have them be draggable. I suspect this is because all the draggable event listeners are bound when the page is loaded, before my new elements are created. Has anyone had any luck using HTML5 to make dynamically added elements draggable? Or is there a way to re-bind event listeners without reloading the page?

Using .bind() with any of the HTML5 drag events doesn't seem to work. i.e,

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

won't ever fire, though .bind() with a click event works fine. I'm guessing this is because "drag" means nothing to jQuery. I am including the draggable="true" HTML tag in the new element, by the way.

So, anyone have success stories for binding the HTML5 drag events to dynamically created elements, or is it not possible? Thanks!

like image 992
Tesslacoiled Avatar asked Nov 17 '14 22:11

Tesslacoiled


People also ask

Is drag and drop possible using HTML5 and how?

Drag and Drop (DnD) is powerful User Interface concept which makes it easy to copy, reorder and deletion of items with the help of mouse clicks. This allows the user to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.

Which HTML supports drag and drop feature?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

Does HTML support drag and drop?

In HTML, any element can be dragged and dropped.


1 Answers

There are two ways to accomplish this. The first is to use some kind of ancestor element that will exist at the time your bind() is called:

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

The second is to structure your code such that your bind function gets called after your newElement gets created:

var $newElement = $('<div class="newElement"></div>');

$newElement.on('drag', function(e){
    console.log('do you even drag, bro?');
});
like image 188
aselbie Avatar answered Sep 19 '22 02:09

aselbie