Chuck
Chuck

Reputation: 452

jQuery's animate() scrollTop property doesn't work on iPad Safari

I have a div that will show a scrollbar if it gets long. It's css is

top: 35px;
overflow: hidden;
position: absolute;
width: 100%;
height: 100%;
bottom: 0px;
overflow-x: hidden;
display: block;

Somehow when I use jQuery (v1.7.1) to scroll this div, it does NOT work on iPad (iOS 8.3) Safari, but it works perfectly on all desktop browsers. This is the code

$('#myDivId').animate({ scrollTop: 100 });

This plain JS code doesn't work either on iPad safari, but works fine on desktop browsers

var myDiv = document.getElementById('myDivId');
myDiv.scrollTop = 100;

Anyone got any ideas on why?

Upvotes: 0

Views: 7139

Answers (1)

baroquedub
baroquedub

Reputation: 962

I had the same problem a while back. I can't remember exactly why but it seems that jQuery animate doesn't work in that scenario for those devices. This works for me:

var scrollOffset = $('#myDivId').offset().top;

if (navigator.userAgent.match(/iPad|iPhone|iPod|Android|Windows Phone/i)) {  

            function customScrollTo(to, duration) {
                var start = 0,
                    change = to - start,
                    currentTime = 0,
                    increment = 20;

                var animateScroll = function(){        
                    currentTime += increment;
                    var val = Math.easeInOutQuad(currentTime, start, change, duration);                        
                    window.scrollTo(0,val);

                    if(currentTime < duration) {
                        setTimeout(animateScroll, increment);
                    }
                };
                animateScroll();
            }

            Math.easeInOutQuad = function (t, b, c, d) {
                t /= d/2;
                if (t < 1) return c/2*t*t + b;
                t--;
                return -c/2 * (t*(t-2) - 1) + b;
            };

            customScrollTo(scrollOffset, 1000);
}else{
            $('#myDivId').animate({
                scrollTop: scrollOffset
            }, 1000, function(){
                $('#myDivId').clearQueue();
            });
}

It uses jQuery animate for normal browsers but uses a custom scroll script for mobile devices. Apologies to the original author, I can't remember where the script came from. Hope this helps.

Upvotes: 5

Related Questions