Created
September 12, 2025 18:38
-
-
Save dlisboa/099a926e0d2ef0dcffa7892f72f73cbe to your computer and use it in GitHub Desktop.
Javascript selection box / mouse up/down/move
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // by goo - https://www.gurukhalsa.me/ | |
| // https://news.ycombinator.com/item?id=45219644 | |
| // creates a selection box like on Desktop OSes | |
| (() => { 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."); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment