โœจdrag the bar

browser โŸฉ event โŸฉ type โŸฉ mouse โŸฉ "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