Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
Add Comment
Please, Sign In to add comment