Created
March 30, 2024 19:07
-
-
Save audinue/8d87b3023552e7ae3d910b7672ebd35e to your computer and use it in GitHub Desktop.
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
.range { | |
position: relative; | |
height: 24px; | |
display: flex; | |
flex-direction: column; | |
justify-content: center; | |
cursor: default; | |
user-select: none; | |
} | |
.range:before { | |
content: ''; | |
height: 2px; | |
background: #999; | |
} | |
.range-start, .range-end { | |
position: absolute; | |
left: -6px; | |
top: 0; | |
width: 12px; | |
height: 100%; | |
} | |
.range-start { | |
background: #f99; | |
} | |
.range-end { | |
background: #99f; | |
} |
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
<link rel="stylesheet" href="range.css"> | |
<script src="range.js"></script> | |
<div class="range"> | |
<div class="range-start"></div> | |
<div class="range-end"></div> | |
</div> | |
<script> | |
addEventListener('range-slide', e => console.log(e.target, e.detail)) | |
// { value: 0..1, isEnd: boolean } | |
</script> |
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
addEventListener('mousedown', e => { | |
if (e.target.matches?.('.range-start,.range-end')) { | |
let handle = e.target | |
let range = handle.parentNode | |
let width = range.offsetWidth | |
let isEnd = handle.matches('.range-end') | |
let friend = isEnd ? range.querySelector('.range-start') : range.querySelector('.range-end') | |
let min = isEnd ? friend.x ?? 0 : 0 | |
let max = isEnd ? width : (friend.x ?? 0) | |
let x = handle.x ?? 0 | |
let mousemove = e => { | |
let newX = Math.max(min, Math.min(x + e.movementX, max)) | |
if (x != newX) { | |
x = newX | |
handle.style.transform = `translate(${x}px,0)` | |
handle.x = x | |
range.dispatchEvent(new CustomEvent('range-slide', { | |
bubbles: true, | |
detail: { | |
isEnd, | |
value: x / width | |
} | |
})) | |
} | |
} | |
let mouseup = e => { | |
removeEventListener('mousemove', mousemove) | |
removeEventListener('mouseup', mouseup) | |
} | |
friend.style.zIndex = 0 | |
handle.style.zIndex = 1 | |
addEventListener('mousemove', mousemove) | |
addEventListener('mouseup', mouseup) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment