|
<html> |
|
|
|
<head> |
|
<style> |
|
#toDrag { |
|
position: absolute; /* Position our square absolutely; you can read more about absolute positioning at https://developer.mozilla.org/en-US/docs/Web/CSS/position */ |
|
width: 100px; |
|
height: 100px; |
|
background-color: lightblue; |
|
} |
|
</style> |
|
</head> |
|
|
|
<body> |
|
<div id='toDrag'></div> |
|
<script> |
|
var square = document.querySelector('#toDrag'); // Grab our #toDrag square |
|
var draggingSquare = false; // Set a flag for whether we're dragging the square |
|
|
|
var mousePosition = { // set up a global variable where we'll store a dictionary of mousePosition coordinates, starting out as null — you can read more about null at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null |
|
'x': null, |
|
'y': null |
|
}; |
|
|
|
var updateMousePosition = function(event) { // Update our mousePosition with the information from the event we pass, you can read more about mouseEvents at https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent |
|
mousePosition.x = event.x; |
|
mousePosition.y = event.y; |
|
}; |
|
|
|
var move = function(element, x, y) { // Move an element's center to x, y |
|
// You can read more about determining the size of elements at https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements |
|
element.style.left = x - element.offsetWidth / 2 + "px"; |
|
element.style.top = y - element.offsetHeight / 2 + "px"; |
|
}; |
|
|
|
square.addEventListener('mousedown', function() { |
|
// When we mousedown on the square, toggle draggingSquare to true |
|
draggingSquare = true; |
|
}); |
|
|
|
square.addEventListener('mouseup', function() { |
|
// When we mouseup on the square, toggle draggingSquare to false |
|
draggingSquare = false; |
|
}); |
|
|
|
window.addEventListener('mousemove', function(event) { // Whenever our mouse moves in the window |
|
updateMousePosition(event); // update our mousePosition dictionary |
|
if (draggingSquare) { // and if we're dragging the square |
|
move(square, mousePosition.x, mousePosition.y); // move the square |
|
} |
|
}); |
|
</script> |
|
</body> |
|
|
|
</html> |