Comment

Comment by goo

Almost perfect. Inspirational.

It just needed to create a little box you can drag around when you click on nothing, like OS desktops have.

So here's the snippet to do that, toss this in the console and live the dream:

(() => { let startX, startY, box, dragging = false;

  const style = document.createElement('style');
  style.textContent = `
    .___selection-box {
      position: absolute;
      pointer-events: none;
      border: 1px dashed #2b76d6;
      background: rgba(43,118,214,0.12);
      z-index: 999999;
    }
  `;
  document.head.appendChild(style);

  function onDown(e) {
    if (e.button !== 0) return; // left click only
    startX = e.pageX;
    startY = e.pageY;
    dragging = true;

    box = document.createElement('div');
    box.className = '___selection-box';
    box.style.left = startX + 'px';
    box.style.top = startY + 'px';
    document.body.appendChild(box);

    e.preventDefault();
  }

  function onMove(e) {
    if (!dragging) return;
    const x = e.pageX, y = e.pageY;
    const left = Math.min(x, startX);
    const top = Math.min(y, startY);
    const width = Math.abs(x - startX);
    const height = Math.abs(y - startY);
    Object.assign(box.style, {
      left: left + 'px',
      top: top + 'px',
      width: width + 'px',
      height: height + 'px'
    });
  }

  function onUp(e) {
    if (!dragging) return;
    dragging = false;
    console.log('Selection rect:', box.getBoundingClientRect());
    box.remove();
    box = null;
  }

  window.addEventListener('mousedown', onDown);
  window.addEventListener('mousemove', onMove);
  window.addEventListener('mouseup', onUp);

  console.log(" Selection enabled. Drag with left mouse button. Check console for rect.");
})();
parent goo 1 year ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton