jQuery ScrollTop to Element ID not working on Safari

Viewed 598

I need a cross-browser solution for scrolling to an element on a page. This code works perfectly on Chrome, but not Safari, nor Safari on mobile. It scrolls to the top of the page, not to the div id:

$(".link").click(function() {
    $("html,body").animate({ scrollTop: $("#div_id").offset().top - 260 }, 1000);
});
1 Answers

According to this issue recorded on github (now closed), if you have the following code in your css:

body{
overflow-x:hidden;
}

, then it will prevent Safari from calculating scrollTop accurately (but it only affects Safari).

If you have hidden overflow css, you could remove it, or a suggested workaround (also in the post) is to use:

const scrollTop = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)

hope this helps

Related