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; });
Draggable Div is a kind of element that you can drag anywhere.
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.
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.
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).
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