views:

51

answers:

4

I'm trying to understand how this drag/drop javascript example would be done in jquery. I'm guessing the jquery version will be cleaner, more efficient, and easier to understand.

+1  A: 

Check out jQueryUI. They have a lot of cool stuff, including drag/drop, that's really easy to use.

Aaron Hathaway
+1  A: 

Take a look on this from Jquery ui

piemesons
+1  A: 

Check out http://jqueryui.com/demos/draggable/ . you can view the source. You'll need to link to jquery and to jquery ui.

Catfish
+2  A: 

This is how i do it w/o using jQuery UI. Assumes you've styled .draggable to also be position: absolute:

var $draggable = null, startX, startY;

$('.draggable').live('mousedown', function(ev) {
    $draggable = $(this);
    var pos = $draggable.position();
    startX = ev.pageX - pos.left;
    startY = ev.pageY - pos.top;
    return false;
});

$(document).bind('mousemove', function(ev) {
    if ($draggable) {
        $draggable.css({ left: ev.pageX - startX, top: ev.pageY - startY});
        return false;
    }
});

$(document).bind('mouseup', function(ev) {
    if ($draggable) {
        $draggable = null;
        return false;
    }
});
Scott Evernden