I am trying to achieve an effect on a site I'm working on, where as the user scrolls vertically, an element slides horizontally the relative amount (i.e. if the user scrolls down by 10% of the document height, the particular element will move to the left by 10% of its own width).
The issue I'm having is that I'm using the touchstart and touchend events to calculate how much the user has scrolled vertically. However, on mobile devices (e.g. iPhone), the document will continue to scroll for a short while after the user finishes swiping and stops touching the screen.
Is there an alternative way to detect the document scrolling on mobile devices that will include the distance scrolled after the touch event ends?
Thanks!
My code:
var wave = $('.front-page__mobile-wave');
var height = $(document).height();
var width = wave.width();
var oneWidth = width/100;
var ts;
$(document).bind('touchstart', function (e){
ts = e.originalEvent.touches[0].clientY;
});
$('.front-page').bind('touchmove', function(e){
var te = e.originalEvent.changedTouches[0].clientY;
var scroll = $(window).scrollTop();
var percentHeight = scroll / height * 100;
var bgSlideForward = oneWidth * percentHeight;
var bgSlideBack = -oneWidth * percentHeight;
if(ts < te){
wave.css('left', bgSlideBack);
} else if (ts > te){
wave.css('left', -bgSlideForward);
}
});
Resolution was to use the scroll event instead of touchstart and touchmove and use variables to keep track of the current vs previous scrollTop, i.e.:
var wave = $('.front-page__mobile-wave');
var height = $(document).height();
var width = wave.width();
var oneWidth = width/100;
var lastScrollTop = 0;
$(window).scroll(function(e){
var scroll = $(window).scrollTop();
var percentHeight = scroll / height * 100;
var bgSlideForward = oneWidth * percentHeight;
var bgSlideBack = -oneWidth * percentHeight;
if(scroll > lastScrollTop){
wave.css('left', bgSlideBack);
} else if (scroll < lastScrollTop){
wave.css('left', -bgSlideForward);
}
lastScrollTop = scroll;
});