Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable div without jQuery UI

I'm trying to make a div draggable without using jQuery UI.

However, I'm stuck with the code below. I understand that I should use the mouse position relative to the container div (in which the div will be dragged) and that I should set the div's offset relative to those values.

I just can't figure out how. Any clues?

This is the code that doesn't (of course) work:

var X, Y;  $(this).mousedown(function() {     $(this).offset({          left: X,          top: Y     }); });  $("#containerDiv").mousemove(function(event) {     X = event.pageX;     Y = event.pageY; }); 
like image 307
holyredbeard Avatar asked Dec 19 '11 23:12

holyredbeard


People also ask

Can Div be draggable?

Draggable Div is a kind of element that you can drag anywhere.

How do you make a div draggable in HTML?

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.

Why is draggable not working?

Check whether your draggable object is already loaded in the viewport. If it is not, it won't work properly. JUST AFTER the draggable object to be absolutely sure that everything is loaded at the correct time. When you'll be sure everything is ok, then you'll be able to refactor.


1 Answers

Here's a really simple example that might get you started:

$(document).ready(function() {     var $dragging = null;      $(document.body).on("mousemove", function(e) {         if ($dragging) {             $dragging.offset({                 top: e.pageY,                 left: e.pageX             });         }     });       $(document.body).on("mousedown", "div", function (e) {         $dragging = $(e.target);     });      $(document.body).on("mouseup", function (e) {         $dragging = null;     }); }); 

Example: http://jsfiddle.net/Jge9z/

I understand that I shall use the mouse position relative to the container div (in which the div shall be dragged) and that I shall set the divs offset relative to those values.

Not so sure about that. It seems to me that in drag and drop you'd always want to use the offset of the elements relative to the document.

If you mean you want to constrain the dragging to a particular area, that's a more complicated issue (but still doable).

like image 60
Andrew Whitaker Avatar answered Sep 21 '22 06:09

Andrew Whitaker