Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created December 17, 2016 04:13
Show Gist options
  • Save remarkablemark/5002d27442600510d454a5aeba370579 to your computer and use it in GitHub Desktop.
Save remarkablemark/5002d27442600510d454a5aeba370579 to your computer and use it in GitHub Desktop.
Basic draggable example using vanilla JavaScript.
'use strict';
/**
* Makes an element draggable.
*
* @param {HTMLElement} element - The element.
*/
function draggable(element) {
var isMouseDown = false;
// initial mouse X and Y for `mousedown`
var mouseX;
var mouseY;
// element X and Y before and after move
var elementX = 0;
var elementY = 0;
// mouse button down over the element
element.addEventListener('mousedown', onMouseDown);
/**
* Listens to `mousedown` event.
*
* @param {Object} event - The event.
*/
function onMouseDown(event) {
mouseX = event.clientX;
mouseY = event.clientY;
isMouseDown = true;
}
// mouse button released
element.addEventListener('mouseup', onMouseUp);
/**
* Listens to `mouseup` event.
*
* @param {Object} event - The event.
*/
function onMouseUp(event) {
isMouseDown = false;
elementX = parseInt(element.style.left) || 0;
elementY = parseInt(element.style.top) || 0;
}
// need to attach to the entire document
// in order to take full width and height
// this ensures the element keeps up with the mouse
document.addEventListener('mousemove', onMouseMove);
/**
* Listens to `mousemove` event.
*
* @param {Object} event - The event.
*/
function onMouseMove(event) {
if (!isMouseDown) return;
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
element.style.left = elementX + deltaX + 'px';
element.style.top = elementY + deltaY + 'px';
}
}
<style>
#element {
width: 100px;
height: 100px;
background: skyblue;
position: relative;
}
</style>
<div id="element"></div>
<script src="draggable-example.js"></script>
<script>
draggable(document.getElementById('element'));
</script>
@mikhoul
Copy link

mikhoul commented Apr 10, 2018

@remarkablemark commented on 16 déc. 2016 à 23:13 UTC−5:

https://jsfiddle.net/remarkablemark/93gfvjmw/

Why when I try to use a "class" instead of an ID it did not work ?

draggable(document.getElementsByClassName('MyClass'));

JsBin: http://jsbin.com/bifinuxevi/1/edit?html,css,js,output

Regards :octocat:

@roflsunriz
Copy link

@mikhoul
draggable(document.getElementsByClassName('MyClass')[0]);

@mrrovot
Copy link

mrrovot commented Sep 19, 2018

This is great, how can I get the element id of the element I dragged the 'draggable el' into
so if I need to drag a key into a box how would I verify that onmouseup that it dragged into the box?

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