Skip to content

Instantly share code, notes, and snippets.

@b-aleksei
Last active December 15, 2020 06:39
Show Gist options
  • Save b-aleksei/f97ce13d1abc724ed192a465244f2d2d to your computer and use it in GitHub Desktop.
Save b-aleksei/f97ce13d1abc724ed192a465244f2d2d to your computer and use it in GitHub Desktop.
range
const range = document.querySelector('.range');
const thumb = document.querySelector('.range__thumb');
let isTouch = false;
let touch = 'pointerdown';
let touchMove = 'pointermove';
let touchUp = 'pointerup';
if ('ontouchstart' in window) {
isTouch = true;
touch = 'touchstart';
touchMove = 'touchmove';
touchUp = 'touchend';
}
thumb.addEventListener(touch, function (evt) {
evt.preventDefault();
const x = (isTouch) ? evt.changedTouches[0].clientX : evt.clientX;
const shiftX = x - thumb.offsetLeft;
const rightEdge = range.offsetWidth - thumb.offsetWidth;
document.addEventListener(touchMove, onMove);
document.addEventListener(touchUp, onPointerUp);
function onMove(e) {
const x = (isTouch) ? e.changedTouches[0].clientX : e.clientX;
let left = x - shiftX;
if (left < 0) {
left = 0;
}
if (left > rightEdge) {
left = rightEdge;
}
thumb.style.left = left + 'px'
}
function onPointerUp() {
document.removeEventListener(touchMove, onMove);
document.removeEventListener(touchUp, onPointerUp);
}
});
/*<div class="range">
<div class="range__truck"></div>
<div class="range__thumb"></div>
</div>*/
/*.range {
margin-top: 30px;
position: relative;
width: 300px;
height: 20px;
display: flex;
align-items: center;
}
.range__truck {
width: 100%;
height: 4px;
background: brown;
border-radius: 18px;
}
.range__thumb {
position: absolute;
top: 0;
left: 0;
width: 18px;
height: 18px;
border-radius: 50%;
background: tan;
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment