Created
June 17, 2015 12:50
-
-
Save tsamb/c7104b230684a2f26177 to your computer and use it in GitHub Desktop.
Simple drag and drop in JavaScript
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
<html> | |
<head> | |
<title>drag and drop demo</title> | |
</head> | |
<body> | |
<div id="box" style="background-color:green;width:100px;height:100px; position:absolute; cursor:pointer"></div> | |
<script type="text/javascript"> | |
// get and name the element | |
var box = document.getElementById("box"); | |
// set a flag as to whether the element is currently being dragged | |
var dragging = false; | |
// listen for mousedown events on the box; call dragStart() when they arrive | |
box.addEventListener("mousedown", dragStart); | |
// every time the mouse is pressed down in the box, add a listener to listen for mouse moves | |
// call dragContinue() when the mouse moves | |
function dragStart(event) { | |
document.addEventListener("mousemove", dragContinue); | |
} | |
function dragContinue(event) { | |
// move the box to the middle of the mouse | |
box.style.left = event.clientX - parseInt(getComputedStyle(box)["width"].slice(0, -2)) / 2; | |
box.style.top = event.clientY - parseInt(getComputedStyle(box)["height"].slice(0, -2)) / 2; | |
// log how many listeners are on the DOM | |
console.log(listenerCount) | |
// add a listener to call dragStop() when the mouse button is release | |
// only add it once (take out this conditional to see how many event listeners are added otherwise) | |
if (!dragging) { | |
document.addEventListener("mouseup", dragStop); | |
dragging = true; | |
}; | |
} | |
// remove both mousemove and mouseup listeners and reset the dragging flag | |
function dragStop(event) { | |
document.removeEventListener("mousemove", dragContinue); | |
document.removeEventListener("mouseup", dragStop); | |
dragging = false; | |
} | |
// Count the number of event listeners on the DOM at any one time (works in Chrome) | |
var listenerCount = 0; | |
(function() { | |
var ael = Node.prototype.addEventListener; | |
Node.prototype.addEventListener = function() { | |
listenerCount++; | |
ael.apply(this, arguments); | |
} | |
var rel = Node.prototype.removeEventListener; | |
Node.prototype.removeEventListener = function() { | |
listenerCount--; | |
rel.apply(this, arguments); | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment