I have a gray div at the bottom of my page and on a single swipe up, I would like the gray div to scroll/slide all the way to the top until it touches the bottom of the blue banner div. Right now when I swipe up it goes about half way up the page and stops and needs to be swiped a couple times before it touches the bottom of the banner div. When the gray div is at the top, I would also like for it to return to its initial position at the bottom of the page on a single swipe down but it takes a couple of swipes for that to happen. Please take a look at my fiddle below and see if you can spot where the problem lies.
Hi @oangodd , I think the issue is that your currentY
is being calculated as a delta (like clientY - startY
) during touch move, but used as an absolute value in the touch end handler. Also note that your maxScroll
is always -0
.
To fix this, you might set a threshold for snapping, and revert to the initial top style if below that threshold… like e.g.:
const sliderContainer = document.querySelector('main')
const sliderContent = document.getElementById('slider-content')
const SNAP_THRESHOLD = 100
let initialTop
let startY
let currentY
let isDragging = false
sliderContainer.addEventListener('touchstart', (e) => {
initialTop = parseInt(window.getComputedStyle(sliderContent).top, 10)
startY = currentY = e.touches[0].clientY
isDragging = true
})
sliderContainer.addEventListener('touchmove', (e) => {
if (!isDragging) return
currentY = e.touches[0].clientY
sliderContent.style.top = `${initialTop - startY + currentY}px`
})
sliderContainer.addEventListener('touchend', () => {
isDragging = false
if (currentY >= 360) {
currentY = 360
} else if (startY - currentY > SNAP_THRESHOLD) {
currentY = 0
} else {
currentY = startY
}
sliderContent.style.top = `${currentY}px`
})
Snapping to the bottom would work analogously.
1 Like
Thanks for replying, your suggestion seems to work. When I swipe up and down on the gray div it goes up and down all the way to the top and bottom of the page smoothly.
1 Like
Glad I could help. :-)