https://jsfiddle.net/f8L300ug/3/
I'm trying to make a simple drag-to-resize function. See the example above.
If the mouse is released outside the <body>, the mouseup event won't be triggered, in contrast to what this post implies: Responding to the onmousemove event outside of the browser window in IE
jsFiddle's drag handler does a good job in this. If the mouse is released outside the element, then unbind the mousemove event; If the mouse is not released outside the element and moves back in, then keep the mousemove event. How can I achieve this?
Here's my code. jsFiddle's resize functionality is not perfect after well. After playing it for a while, I triggered a bug and my CSS panel is gone, so I can't post my CSS code here...
JS:
var initialX;
var leftPanel = document.getElementById("left");
var rightPanel = document.getElementById("right");
var resizePanels = function(e){
var deltaX = e.clientX - initialX;
var bodyWidth = parseInt(window.getComputedStyle(leftPanel).width);
initialX = e.clientX;
var newWidth = bodyWidth + deltaX;
leftPanel.style.width = newWidth + "px";
rightPanel.style.width = (parseInt(window.getComputedStyle(document.body).width) - newWidth)*0.9 + "px";
}
var bodyUnbindResize = function(){
document.body.removeEventListener("mousemove", resizePanels)
document.body.style.cursor = "default";
}
document.getElementById("dragger").addEventListener("mousedown", function(){
document.body.addEventListener("mousemove", resizePanels)
document.body.addEventListener("mouseup", bodyUnbindResize)
document.body.style.cursor = "col-resize";
});
HTML:
<div id="left" class="grid">
</div>
<div id="dragger" class="grid"></div>
<div id="right" class="grid">
</div>
And please improve my code if you have a better way. This is the first time I use vanilla JS to do this, so this might not be the best way. Thanks!