How do I make an element, e.g. a div, draggable using jQuery?
To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page. Our example creates an interface to rearrange columns that have been laid out with CSS Grid.
Draggable() Method This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port.
By default, only image and text can be draggable. To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.
You can do with jquery only, without jquery UI:
function handle_mousedown(e){ window.my_dragging = {}; my_dragging.pageX0 = e.pageX; my_dragging.pageY0 = e.pageY; my_dragging.elem = this; my_dragging.offset0 = $(this).offset(); function handle_dragging(e){ var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0); var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0); $(my_dragging.elem) .offset({top: top, left: left}); } function handle_mouseup(e){ $('body') .off('mousemove', handle_dragging) .off('mouseup', handle_mouseup); } $('body') .on('mouseup', handle_mouseup) .on('mousemove', handle_dragging); } $('#b').mousedown(handle_mousedown);
First load the jQuery UI:
<link type="text/css" href="css/themename/jquery-ui-1.7.1.custom.css" rel="Stylesheet" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
Then use jQuery UI draggable method:
<script type="text/javascript"> $(function() { $("#b").draggable(); }); </script>
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