views:

156

answers:

2

What would be the best way to make an element draggable when clicking anywhere in the window?

Would I have to use a container <div> that covers the whole window?

I tried making the body draggable but that didn't work.

The problem with using a container <div> is that it moves and therefore doesn't cover the whole of the screen any more after it has been dragged.

What about making a really vast container <div> that spans a large number of pixels in every direction so you would never get to the edge of it. Is that a bad idea?

The idea (simplified) is to have a page with a square in the middle that can be dragged by dragging any part of the window.

Here's a wonderfully unnecessary mockup :)

alt text

I'm trying with a full screen div, but when I reset it, the element within it moves back with it.. http://jsfiddle.net/LUFf6/

+1  A: 

it really depends on what you are trying to achieve, so we'll need to know a bit more really.
You could just move the draggable div to the top left of the screen and full width/height after each "drop" event?

I personally wouldn't go down the 'vast container' route though.

danrichardson
I updated my question. I'll try what you suggested with resetting the full screen div. Sounds like the way I'll have to go if there's no built in feature to achieve it.
Acorn
+1  A: 

EDIT: revised to include mouse offset from the div.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"&gt;&lt;/script&gt;
<script>
function doMove(e) {
  var $d = $('#myDiv');
  var off = $d.offset();
  var left = e.pageX + $d.data('left');
  var top = e.pageY + $d.data('top');
  $d.offset({left: left, top: top});
};
$(function() {
  $(document).mousedown(function(e) {
     var $d = $('#myDiv');
     var off = $d.offset();
     $d.data('left',off.left - e.pageX);
     $d.data('top',off.top - e.pageY);     
     $(document).bind('mousemove', doMove);
  }).mouseup(function(e) {
     $(document).unbind('mousemove',doMove);
  });
});
</script>
<style>
div#myDiv {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  top: 100px;
  left: 100px;
}
</style>
<div id="myDiv"></div>
blesh
Thanks, but I really want to use jquery-ui for the dragging :(
Acorn
Well you could do that, but you'd have to alter jquery ui yourself to do it. draggable() doesn't quite behave like that.
blesh
I'm also not sure what you'd gain by having to use jquery ui.
blesh
I'd definitely look at other options, but do you not think It's achievable with jquery-ui? It seems to just about work, apart from the object being moved back to its original position when I reset the full screen container.. http://jsfiddle.net/LUFf6/
Acorn
I don't know why I'm messing around with jquery-ui, I should just use your beautiful solution. Thank you!
Acorn