Last active
March 17, 2023 18:54
-
-
Save Polkovn1k/31356d3b104d796dc045a2189c7d0004 to your computer and use it in GitHub Desktop.
Custom scroll by translateX (HTML + CSS +JS)
This file contains 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
<section> | |
<div class="translate-x-elem"></div> | |
</section> | |
<style> | |
section { | |
width: 800px; | |
min-height: 100px; | |
background: orange; | |
margin: 100px auto 100px auto; | |
overflow: hidden; | |
} | |
.translate-x-elem { | |
width: 1300px; | |
min-height: 80px; | |
background: linear-gradient(135deg,#2aa34f,#2e9577 33%,#6c6dbe 66%,#a979c3); | |
/* touch-action: none - обязательно, для нормальной работы на мобильных устройствах */ | |
touch-action: none; | |
} | |
</style> | |
<script> | |
let options = { | |
//options.elem обязательно - тут указываем DOM который надо скролить | |
elem: document.querySelector('.translate-x-elem'), | |
startPosition: 0, | |
endPosition: 0, | |
currentPosition: 0, | |
movePosition: 0, | |
}; | |
const touchMoveHandler = (evt) => { | |
calculateMovePosition(evt.clientX); | |
//Тут можно поставить функцию - ограничитель скрола по условию | |
options.elem.style.transform = `translateX(${options.currentPosition}px)`; | |
document.addEventListener('pointerup', touchEndHandler); | |
}; | |
const calculateMovePosition = (elemClientX) => { | |
options.movePosition = elemClientX - options.startPosition; | |
options.currentPosition = options.endPosition + options.movePosition; | |
}; | |
const touchEndHandler = () => { | |
options.endPosition = options.currentPosition; | |
removeHandler(); | |
}; | |
const removeHandler = () => { | |
document.removeEventListener('pointermove', touchMoveHandler); | |
document.removeEventListener('pointerup', touchEndHandler); | |
}; | |
const scrollImitationHandler = (evt) => { | |
//Условие - запускать цепочки обработчиков, только если событие произошло на нашем элементе | |
if (!options.elem.contains(event.target)) return; | |
options.startPosition = evt.clientX; | |
document.addEventListener('pointermove', touchMoveHandler); | |
}; | |
document.addEventListener("pointerdown", scrollImitationHandler); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment