I have a problem with scroll to element on mobile Safari in iframe (it works on other browsers, including Safari on mac).
I use scrollIntoView
. I want to scroll when all content has been rendered. Here is my code:
JavaScript
x
34
34
1
var readyStateCheckInterval = setInterval(function () {
2
if (document.readyState === "complete") {
3
clearInterval(readyStateCheckInterval);
4
$browser.notifyWhenNoOutstandingRequests(function () {
5
if (cinemaName != null && eventId == null) {
6
scrollToCinema();
7
} else {
8
scrollToEvent();
9
}
10
});
11
}
12
}, 10);
13
14
15
function scrollToEvent() {
16
var id = eventId;
17
var delay = 100;
18
19
if (cinemaName != null) {
20
id = cinemaName + "#" + eventId;
21
}
22
23
if ($rootScope.eventId != null) {
24
id = $rootScope.cinemaId + "#" + $rootScope.eventId;
25
}
26
27
$timeout(function () {
28
var el = document.getElementById(id);
29
if (el != null)
30
el.scrollIntoView(true);
31
$rootScope.eventId = null;
32
}, delay);
33
}
34
Advertisement
Answer
ScrollIntoView does not work (currently). But you can manually calculate the position of the element and scroll to it. Here is my solution
JavaScript
1
2
1
const element = document.getElementById('myId')
2
Pass the element to this function
JavaScript
1
19
19
1
/** Scrolls the element into view
2
* Manually created since Safari does not support the native one inside an iframe
3
*/
4
export const scrollElementIntoView = (element: HTMLElement, behavior?: 'smooth' | 'instant' | 'auto') => {
5
6
let scrollTop = window.pageYOffset || element.scrollTop
7
8
// Furthermore, if you have for example a header outside the iframe
9
// you need to factor in its dimensions when calculating the position to scroll to
10
const headerOutsideIframe = window.parent.document.getElementsByClassName('myHeader')[0].clientHeight
11
12
const finalOffset = element.getBoundingClientRect().top + scrollTop + headerOutsideIframe
13
14
window.parent.scrollTo({
15
top: finalOffset,
16
behavior: behavior || 'auto'
17
})
18
}
19
Pitfalls: Smooth scroll also does not work for ios mobile, but you can complement this code with this polyfill