Skip to content

Instantly share code, notes, and snippets.

@ShoOgino
Created March 13, 2023 13:46
Show Gist options
  • Save ShoOgino/ec75ed4136003795a5c70ec5a000ca9a to your computer and use it in GitHub Desktop.
Save ShoOgino/ec75ed4136003795a5c70ec5a000ca9a to your computer and use it in GitHub Desktop.
Resizable Sidebar
<div class="container">
<aside id="sidebar"></aside>
<div class="resize-handle--x" id="resize-handle" data-target="aside"></div>
<main></main>
</div>
const resizeData = {
tracking: false,
startCursorScreenX: null,
maxWidth: 500,
minWidth: 350
};
document.getElementById('resize-handle').addEventListener('mousedown', event => {
event.preventDefault();
event.stopPropagation();
resizeData.startWidth = document.getElementById('sidebar').offsetWidth;
resizeData.startCursorScreenX = event.screenX;
resizeData.tracking = true;
});
document.addEventListener('mousemove', event => {
if (resizeData.tracking) {
const cursorScreenXDelta = event.screenX - resizeData.startCursorScreenX;
let newWidth = Math.min(resizeData.startWidth + cursorScreenXDelta, resizeData.maxWidth);
newWidth = Math.max(resizeData.minWidth, newWidth);
document.getElementById('sidebar').style.width = newWidth + 'px';
}
})
document.addEventListener('mouseup', event => {
if(resizeData.tracking) resizeData.tracking = false
});
// $(window).on('mousemove', null, null, _.debounce((event) => {
// if (resizeData.tracking) {
// const cursorScreenXDelta = event.screenX - resizeData.startCursorScreenX;
// let newWidth = Math.min(resizeData.startWidth + cursorScreenXDelta, resizeData.maxWidth);
// newWidth = Math.max(resizeData.minWidth, newWidth);
// document.getElementById('sidebar').style.width = newWidth + 'px';
// }
// }, 1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
html {
height: 100%;
}
body {
box-sizing: border-box;
height: 100%;
margin: 0;
}
.container {
height: 100%;
overflow: hidden;
display: flex;
& > aside {
flex: none;
min-width: 350px;
}
& > main {
flex: 1;
}
}
.resize-handle--x {
flex: none;
position: relative;
box-sizing: border-box;
width: 5px;
height: 100%;
cursor: col-resize;
border-left: 1px solid #ccc;
-webkit-touch-callout: none;
user-select: none;
&:hover,
&:active {
border-color: lightblue;
border-style: double;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment