JAVASCRIPT
Create a Resizable DOM Element
Build custom resizable elements using JavaScript's mouse events to dynamically adjust dimensions, offering advanced UI customization.
document.addEventListener('DOMContentLoaded', () => {
const resizable = document.getElementById('myResizableDiv');
let isResizing = false;
// Create a resize handle element
const handle = document.createElement('div');
handle.style.width = '10px';
handle.style.height = '10px';
handle.style.background = 'red';
handle.style.position = 'absolute';
handle.style.bottom = '0';
handle.style.right = '0';
handle.style.cursor = 'se-resize';
resizable.appendChild(handle);
handle.addEventListener('mousedown', (e) => {
isResizing = true;
e.preventDefault(); // Prevent text selection
document.body.style.cursor = 'se-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const newWidth = e.clientX - resizable.getBoundingClientRect().left;
const newHeight = e.clientY - resizable.getBoundingClientRect().top;
// Ensure minimum dimensions
resizable.style.width = Math.max(50, newWidth) + 'px';
resizable.style.height = Math.max(50, newHeight) + 'px';
});
document.addEventListener('mouseup', () => {
isResizing = false;
document.body.style.cursor = 'default';
});
});
/*
HTML structure example:
<style>
#myResizableDiv {
width: 200px;
height: 150px;
border: 2px solid #333;
position: relative;
background-color: lightgoldenrodyellow;
overflow: hidden;
}
</style>
<div id="myResizableDiv">Resizable Content</div>
*/
How it works: This code enables dynamic resizing of a DOM element. It attaches a 'mousedown' listener to a small 'handle' element, setting a 'isResizing' flag. As the mouse moves ('mousemove'), the element's width and height are updated based on the cursor's position relative to the element's top-left corner. 'mouseup' resets the flag, stopping the resizing process. This provides a user-interactive way to adjust element dimensions.