Spark - Draggable

A draggable div running off Spark. http://wolfy87.github.com/Spark/

by Oliver Caldwell

HTML

<script src="http://sparkjs.co.uk/assets/downloads/Spark-v1.3.5.js"></script>
<p>Click and drag the box</p>
<div class='draggable'></div>

CSS

div.draggable {
    width: 100px;
    height: 100px;
    background-color: #EEEEEE;
    position: absolute;
    margin: 0;
    
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    
    -webkit-box-shadow: 0 0 5px #777777;
    -moz-box-shadow: 0 0 5px #777777;
    box-shadow: 0 0 5px #777777;
}

p {
    color: #333333;
    font-family: helvetica,arial,sans-serif;
    margin: 0;
}

html, body {
    width: 100%;
    height: 100%;
    position: relative;
    padding: 0;
}

JavaScript

// Set up the variables
var mouseDown = false;
var offset = {x:0, y:0};

// IE Selection fix
$('div.draggable').attribute().onselectstart = function () {
    return false;
}

// Good browser selection fix
$('div.draggable').attribute().onmousedown = function () {
    return false;
}

// On mouse down, set the listener to true
$('div.draggable').event('mousedown', function(e) {
    mouseDown = true;
    offset.x = e.pageX - $('div.draggable').location().x;
    offset.y = e.pageY - $('div.draggable').location().y;
});

// On mouse up, set the listener to false
$('body').event('mouseup', function(e) {
    mouseDown = false;
});

// On mouse move, if the listener is true, move the div
$('body').event('mousemove', function(e) {
    if(mouseDown == true)
        $('div.draggable').location(e.pageX - offset.x, e.pageY - offset.y);
});