I\'ve been trying to use ondrag() and some other functions on a div rendered dynamically on an HTML page.
None of these events
Have a look at this documentation: https://developer.mozilla.org/En/DragDrop/Drag_and_Drop
Note: It does not work in every browser.
If you want a cross-browser support use jQuery: http://jqueryui.com/demos/draggable/
jQuery example:
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
<script>
$(function() {
$( "#draggable" ).draggable({
drag: function(event, ui) {}
});
});
</script>
Another example:
<div id="toBeDragged" draggable="true">
This text <strong>may</strong> be dragged.
</div>
<script>
document.getElementById('toBeDragged').addEventListener('dragstart', function(event) {
event.dataTransfer.setData('text/plain', 'This text may be dragged');
});
</script>
An easy way to do this is with jQuery UI, make sure you use it after your dynamic div has been rendered.
$(document).ready(function () {
$('.my_draggable_elements').draggable({
drag: function(){
// do something
}
});
});
Is there content in the div? I don't think it's the element itself that gets dragged in this particular event.
I haven't used drag myself much but I believe it's the drag "edit action" - eg selecting text and dragging it within a textbox/textarea.
You may need to implement your own onmousedown() onmouseup() and onmousemove() handlers for the functionality I think you're after
Short answer: <div>-s are not draggable by default, unlike <a>-s. You must add draggable=true:
<div draggable=true ondragstart=...>HTML</div>
Works on Firefox 75 like that.