jQuery simple drag
Very basic use of jQuery by itself to drag an object around
by craic
HTML
<script src="http://ajax.cdnjs.com/ajax/libs/raphael/1.5.2/raphael-min.js"></script>
<div id="box"></div>
CSS
#box {
background-color: #808;
width: 50px;
height: 50px;
border: 1px solid black;
left: 100px;
top: 100px;
position: absolute;
}
JavaScript
// Interactions using JQuery events
// Drag an object around the canvas
var drag = {x: 0, y: 0, state: false};
var el_coords = {x: 0, y: 0 };
var delta = {x: 0, y: 0 };
var box = $('#box');
var offset = box.offset();
box.mousedown(function(e) {
if(!drag.state) {
drag.x = e.pageX;
drag.y = e.pageY;
offset = this.offset();
el_coords.x = offset.left;
el_coords.y = offset.top;
this.style.backgroundColor = '#f00';
drag.state = true;
}
return false;
});
box.mousemove(function(e) {
if(drag.state) {
this.style.backgroundColor = '#f0f';
delta.x = e.pageX - drag.x;
delta.y = e.pageY - drag.y;
box.offset({top: el_coords.y + delta.y,
left: el_coords.x + delta.x });
offset = this.offset();
el_coords.x = offset.left;
el_coords.y = offset.top;
drag.x = e.pageX;
drag.y = e.pageY;
}
});
box.mouseup(function() {
drag.state = false;
this.style.backgroundColor = '#808';
});
box.mouseout(function() {
box.mouseup();
});