jQuery Draggable
A Very simple plugin for dragging elements (not drag and drop, just moving)
by amindunited
HTML
<div class="draggable" id="firstDiv">
<div class="handle"></div>
First Div
</div>
<div class="draggable" id="secondDiv">
<div class="handle"></div>
Second Div
</div>
CSS
.draggable {
width: 120px;
position:absolute;
top:10;
left: 10px;
}
#secondDiv{
top:10;
left: 140px;
}
.handle {
background-color: #ededed;
border-radius: 5px;
height: 20px;
}
JavaScript
(function ($){
//An object to hold the default values, and the callback functions
var defaults = {
handle:'.handle',
//When writting callback functions
//Note that the events do not occur on the given jQuery element
//to get a reference to that element use e.data.$this
onMouseDown:function(e){},
onMouseUp:function(e){},
onMouseMove:function(e){}
};
//An object to hold the functions of the plugin
var methods = {
init: function(options){
//Use each to individually apply settings and listeners
return this.each(function(){
var $this = $(this);
var settings = $this.data('draggable');
//If settings haven't been previously created, create them now
if (typeof settings == 'undefined') {
settings = $.extend({}, defaults, options);
$this.data('draggable', settings)
} else {
settings = $.extend({}, defaults, options);
}
//Add the mouse down listener to the "handle"
//We pass {$this} so that we can back reference 'this' element from the event (because the event occurs on the "handle")
$this.find(settings.handle).on('mousedown', {$this:$this}, methods.mouseDown);
});
},
mouseDown: function(e){
//Stop if mouseDown wasn't a left click
if ( e.which != 1 ) {
return $(this);
}
e.preventDefault();
//Get the element that we want to reference is not the event.target
//...it is passed as event.data.$this
var $this = e.data.$this;
var settings = $this.data('draggable');
//Set the mouse down positions so we can do calculations based on the original offsets
...