coderholic

jQuery Draggable Implementation

jQuery UI is an excellent add-on library for jQuery that provides all sorts of UI widgets, effects and behaviours. One particularly useful function is provides is to make any element on the page draggable, so that it can be moved about with the mouse.

Because of all the features that jQuery UI provides the library is fairly large, about 450KB uncompressed. It is possible to only include specific parts of the library, but even the bare minimum required for the draggables feature weighs in at just over 40KB uncompressed.

Therefore I decided to write my own lightweight draggable implementation using only jQuery. The code is shown below:

// Make an element draggable using jQuery 
var makeDraggable = function(element) {
    element = jQuery(element);
    
    // Move the element by the amount of change in the mouse position
    var move = function(event) {
        if(element.data('mouseMove')) {
            var changeX = event.clientX - element.data('mouseX');
            var changeY = event.clientY - element.data('mouseY');
        
            var newX = parseInt(element.css('left')) + changeX;
            var newY = parseInt(element.css('top')) + changeY;

            element.css('left', newX);
            element.css('top', newY);
        
            element.data('mouseX', event.clientX);
            element.data('mouseY', event.clientY);                                       
        }
    }
    
    element.mousedown(function(event) {
        element.data('mouseMove', true);
        element.data('mouseX', event.clientX);
        element.data('mouseY', event.clientY);                               
    });
    
    element.parents(':last').mouseup(function() {
        element.data('mouseMove', false);
    });

    element.mouseout(move);            
    element.mousemove(move);           
}

The element you pass to makeDraggable should already have absolute or fixed CSS positioning, and a top and left CSS value set. Something like the following:

<div id='draggable' style='position: absolute; top: 100; left: 200; padding: 50px; background: black; border: 2px solid #aaa;'>
This box is draggable!
</div>
<script type="text/javascript">
makeDraggable(jQuery('#draggable'));
</script>

Then just click on the div and move the mouse to drag it around.

Obviously it isn't as flexible as the jQuery UI version, but it is a useful alternative if you want to save on the amount of data your user's will need to download and you don't require any other jQuery UI features.

Posted on 16 Feb 2009
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.