Skip to content

Instantly share code, notes, and snippets.

@Polkovn1k
Last active March 17, 2023 18:54
Show Gist options
  • Save Polkovn1k/31356d3b104d796dc045a2189c7d0004 to your computer and use it in GitHub Desktop.
Save Polkovn1k/31356d3b104d796dc045a2189c7d0004 to your computer and use it in GitHub Desktop.
Custom scroll by translateX (HTML + CSS +JS)
<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