Skip to content

Instantly share code, notes, and snippets.

@mbritton
Created March 29, 2013 18:24
Show Gist options
  • Select an option

  • Save mbritton/5272601 to your computer and use it in GitHub Desktop.

Select an option

Save mbritton/5272601 to your computer and use it in GitHub Desktop.
Snap an element to the mouse
<script>
var mouseIsDown = false;
function init() {
document.onmousedown = function(e) {
mouseIsDown = true;
};
document.onmouseup = function(e) {
mouseIsDown = false;
};
document.onmousemove = function(e) {
var toPickUp = document.getElementById('draggable00');
if (mouseIsDown) {
snapToMouse(toPickUp);
toPickUp.style['background-color'] = '#FF0000';
} else {
toPickUp.style['background-color'] = '#000000';
}
};
}
function snapToMouse(obj) {
obj.style['left'] = window.event.clientX+'px';
obj.style['top'] = window.event.clientY+'px';
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment