6
votes

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!

1
You need to use event delegation or add the event listeners after the new elements have been addedPatrick Evans
@ Juhana It's a similar question, but I'm already using .on() binding, which works great for jQuery events. The issue is that I'm trying to achieve this with the HTML5 draggable events. I'll try to clarify my question a bit. Thanks!Tesslacoiled
@patrickEvans, I think this question has been marked as duplicate in error. Would you or Juhana please consider re-opening it? I have been unable to find information specific to binding the HTML5 drag events anywhere else. Thanks!Tesslacoiled
No you're problem is the same as in the marked question just substitute the event name they are using for your drag/drop event names. You cant just use .on you have to use a static parent element (one that does not get changed) document is often used. See this Demo (drag red square to green one)Patrick Evans
@patrickEvans Awesome! You're right. I haven't been able to successfully implement it myself, but your example proves that it's possible. Thanks for taking the time to get back to me- I really appreciate it.Tesslacoiled

1 Answers

8
votes

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?');
});