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!
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.
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.
In HTML, any element can be dragged and dropped.
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?');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With