drag the bar

browsereventtypemouse ⟩ "mousemove" ⟩ example ⟩ drag the bar

drag the bar to change its width.

  • bar.onmousedown -> listen to "mousemove" events

  • "mousemove" with event.buttons = 0 ("mouseup" on anything) -> stop listening.

const { log } = console
const {max} = Math;

// ⭐️ import
import { $, $all, elem } from './js/ext/Node_ext.js'; // Node extension
// --------------------------------------------------------------------

let lastX;                 // tracks the last observed mouse X position

const bar = $("#bar");
const span = $('#width');

span.textContent = bar.offsetWidth + 'px';

// bar.onmousedown
bar.addEventListener("mousedown", event => {
    
    // ⭐️ left mouse down 
    //   -> 1. register window.onmousemove  
    //   -> 2. prevent selection
    if (event.button === 0) {
        
        lastX = event.clientX;
        
        // ⭐️ the "mousemove" handler is registered on the whole `window`. 
        //    Even if the mouse goes outside of the bar during resizing, 
        //    as long as the button is held we still want to update its size.
        window.addEventListener("mousemove", onDrag);
        log(`➕ window.onmousemove: handler registered ...`);
        
        // ⭐️ prevent selection (not working for tablets?)
        event.preventDefault();     
    }
    
});

// window.onmousemove
function onDrag(event) {
    
    // ⭐️ when mouse button released (stops dragging) -> stop resizing
    //    when `event.buttons = 0`, no buttons are down. (note the plural)
    if (event.buttons === 0) {
        window.removeEventListener("mousemove", onDrag);
        log(`➖ window.onmousemove: handler removed ...`);
        return;
    }

    // ⭐️ when mouse button held (dragging) -> resize bar
    let dx = event.clientX - lastX;
    let newWidth = max(10, bar.offsetWidth + dx);    // width >= 10px
    bar.style.width = newWidth + "px";
    span.textContent = newWidth + 'px';
    lastX = event.clientX;
}

Last updated