Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an element draggable in jQuery?

How do I make an element, e.g. a div, draggable using jQuery?

like image 903
zjm1126 Avatar asked Mar 11 '10 10:03

zjm1126


People also ask

How do you make a draggable element?

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.

What is jQuery draggable?

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.

How do you make a draggable object in Javascript?

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.


2 Answers

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); 
like image 138
user982671 Avatar answered Oct 04 '22 18:10

user982671


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> 
like image 35
Elzo Valugi Avatar answered Oct 04 '22 16:10

Elzo Valugi