Skip to content

Instantly share code, notes, and snippets.

@kebman
Last active February 17, 2016 23:01
Show Gist options
  • Select an option

  • Save kebman/3f4df42d434124e82391 to your computer and use it in GitHub Desktop.

Select an option

Save kebman/3f4df42d434124e82391 to your computer and use it in GitHub Desktop.
Example of a freely draggable box element made with HTML5 and JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Movable Element</title>
<meta charset="utf-8">
<style type="text/css">
#testBox {
/* define shape and colour */
width: 50px; height: 50px;
background-color: #ddd;
/* important */
position: relative;
}
</style>
</head>
<body>
<header>
<h1>Make a box element movable using JavaScript</h1>
</header>
<article>
<h1>Test Area</h1>
<div id="testBox"></div>
</article>
</body>
<script>
// get the box element using DOM
var box = document.getElementById("testBox");
// initialize the x and y pos variables (pos is short for 'position')
var xPos;
var yPos;
// get offset of the box to justify with mouse pos later
var xOffset = box.offsetLeft;
var yOffset = box.offsetTop;
// check if the mouse is clicked and held down inside the box
box.addEventListener('mousedown', function (e) {
// get mouse pos at the time of the click to calculate offset
var xS = e.pageX-box.offsetLeft;
var yS = e.pageY-box.offsetTop;
// declare the pos function within the scope of the mousedown listener
function getMousePos(e) {
// get actual mouse position
xPos = e.pageX;
yPos = e.pageY;
// move box according to mouse pos,
// but justify for offset and 'click pos'
box.style.left = xPos-xOffset-xS + "px";
box.style.top = yPos-yOffset-yS + "px";
}
// listen for mouse movements, and loop the pos function for as long as the mouse button is held down
document.onmousemove = getMousePos;
// prevent cursor change
e.preventDefault();
}, false);
box.addEventListener('mouseup', function (e) {
// stop running the listener
document.onmousemove = null;
}, false);
</script>
</html>
@kebman

kebman commented Feb 17, 2016

Copy link
Copy Markdown
Author

Check out the live example on JS Fiddle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment