You said at the beginning:
Trying to work backwards from something that’s broken to something that works can be a complicated process due to many assumptions that are made.
Instead of backtracking, I’ll start with working code (always a bonus) and try to use more appropriate techniques to get the desired result instead.
Extracting the mousemove() function from the mousedown event listener, there is a problem where it says: Uncaught ReferenceError: draggable is not defined
What’s happening is that the mousedown function wants to update draggable, and mousemove wants to use that draggable information. When multiple functions want to access the same variable, you set the variable to a higher common parent location, so that one function can update it and the other function can access it.
In this case, I defined draggable in the same place as mainBox and handles. (yes, I renamed MainBox to the more appropriate mainBox too).
document.addEventListener('DOMContentLoaded', function() {
var mainBox = document.querySelector("#MainBox");
var handles = document.querySelectorAll(".handle");
var draggable;
This way we can update draggable from mousedown() function:
mainBox.addEventListener("mousedown", function(ev) {
var isResizing = false;
draggable = ev.target;
and we can access the draggable variable from the mousemove() function.
function mousemove(e) {
const draggableRect = draggable.getBoundingClientRect();
const parentRect = mainBox.getBoundingClientRect();
Here is the updated code https://jsfiddle.net/fqo1tx0m/