Android/iOS webview jQuery.animate({scrollTop: y}) position Incorrect [Solved]

TL;DR; Your line is too long. Add word-break: break-all; to your CSS element that is in trouble.

Problem:

This is not obvious in iOS but very obvious in Android.

  • Assume that you have a checkbox on the top of the page. And the page is so long that you need to scroll to the bottom to see it all.
  • Moreover, there are so many long text that a line will be wrapped to another new line. (Like a Terms and Conditions page)

Now, assume that you have a button at the bottom of your page that will use jQuery.animate({scrollTop: <some_number>}); to scroll to that checkbox. <some_number> is the offset().top position of that checkbox element.

  • Now open your Android webview in app, load that page
  • Manually scroll to the bottom of the page, and then tap the button to scroll to the checkbox element at the top.
  • You will not be able to see the checkbox element. Because the scrollTo position is incorrect.

Let me say that again: this would not happen (at the time of this writing) in iOS webview.

Solution:

My colleague found that the reason is simply because: your line is too long.

When a line is too long, it will be wrapped to the new line. However from the browser point of view, the position of each element is unchanged, i.e. not affected by the new wrapped line.

To solve the problem, applied the CSS to the parent HTML element, or the HTML element that is too long, below:

<your_CSS_element>{ 
 word-break: break-all; 
}

For example, to me it is:

.container{
 word-break:break-all;
}

And then all the positions which is too long is well calculated again. Problem solved.

Hope it helps someone.