Created
June 20, 2012 15:05
-
-
Save kenoir/2960345 to your computer and use it in GitHub Desktop.
Simple cross browser element dragging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Draggable = function(element) { | |
element.addEventListener('mousedown', Draggable.mousedown, false); | |
document.addEventListener('mouseup', Draggable.mouseup, false); | |
} | |
Draggable.mousedown = function(e) { | |
e.target.style.position = 'relative'; | |
document.addEventListener('mousemove', Draggable.mousemove, false); | |
var startingPosition = Draggable.mouseposition(e); | |
var targetPostion = Draggable.targetposition(e); | |
Draggable.offset = { | |
x: targetPostion.x - startingPosition.x, | |
y: targetPostion.y - startingPosition.y, | |
} | |
Draggable.dragging = e.target; | |
} | |
Draggable.mousemove = function(e) { | |
var mouseposition = Draggable.mouseposition(e); | |
var moveposition = { | |
x: mouseposition.x + Draggable.offset.x, | |
y: mouseposition.y + Draggable.offset.y | |
} | |
Draggable.dragging.style.left = moveposition.x + 'px'; | |
Draggable.dragging.style.top = moveposition.y + 'px'; | |
} | |
Draggable.mouseup = function(e) { | |
document.removeEventListener('mousemove', Draggable.mousemove, false); | |
} | |
Draggable.targetposition = function(e) { | |
var extractInt = function(value) { | |
var n = parseInt(value); | |
return n == null || isNaN(n) ? 0 : n; | |
} | |
return { | |
x: extractInt(e.target.style.left), | |
y: extractInt(e.target.style.top), | |
} | |
} | |
Draggable.mouseposition = function(e) { | |
var posx = 0; | |
var posy = 0; | |
if (!e) var e = window.event; | |
if (e.pageX || e.pageY) { | |
posx = e.pageX; | |
posy = e.pageY; | |
} | |
else if (e.clientX || e.clientY) { | |
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; | |
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; | |
} | |
return { | |
x: posx, | |
y: posy | |
}; | |
} | |
var draggableDiv = document.getElementById("dragDiv"); | |
var anotherDraggableDiv = document.getElementById("dragAnotherDiv"); | |
Draggable(draggableDiv); | |
Draggable(anotherDraggableDiv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment