split-pane-test
by Richard Hunter
HTML
<div id="container" class="container">
<div id="first" class="pane first"></div>
<div id="splitter" class="splitter">
<div class="split-line"></div>
</div>
<div id="second" class="pane second"></div>
</div>
CSS
* {
box-sizing: border-box;
}
.container {
width: 70%;
height: 400px;
background: pink;
margin: auto;
position: relative;
}
.pane {
position: absolute;
margin: 2px;
}
.first {
inset: 0 50% 0 0;
background: blue;
margin-left: 0;
}
.second {
inset: 0 0 0 50%;
background: coral;
margin-right: 0;
}
.splitter {
position: absolute;
width: 6px;
z-index: 1;
inset: 0 0 0 50%;
margin-left: -3px;
cursor: ew-resize;
}
.splitter:hover .split-line {
background: red;
position: absolute;
inset: 0 0 0 2px;
width: 2px;
}
JavaScript
function mousemove(event) {
event.preventDefault();
const {
left,
width
} = container.getBoundingClientRect();
let firstWidth = ((event.clientX - left) / width) * 100;
firstWidth = Math.max(20, firstWidth);
firstWidth = Math.min(90, firstWidth);
const secondWidth = 100 - firstWidth;
setFirstWidth(firstWidth);
setSecondWidth(secondWidth);
setSplitterPosition(firstWidth);
console.log(firstWidth);
}
function setFirstWidth(width) {
first.style.inset = `0 ${100 -width}% 0 0`;
}
function setSecondWidth(width) {
second.style.inset = `0 0 0 ${100 -width}%`;
}
function setSplitterPosition(width) {
splitter.style.inset = `0 0 0 ${width}%`;
}
setFirstWidth(75);
setSecondWidth(25);
setSplitterPosition(75);
splitter.addEventListener('mousedown', () => {
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', () => {
window.removeEventListener('mousemove', mousemove)
}, {
once: true
});
});