简体   繁体   中英

ScrollTop not working in Chrome/Safari

I have a form within a loop on our site and when someone submits the form then a query string is added to the url something like "?updated=111". Then my JQuery script checks the url for the number and scrolls to that div once the form is submitted and page reloads.

This script is working fine in Firefox but doesn't work as well in Chrome or Safari. For example, say on my page I have 25 posts, and each posts has its form. Lets say I submit the form on post number 25 (the last one) then when the page reloads on chrome the window scrolls but not all the way to #div25 sometimes it works ( for like 1 -5) other times it will only scroll to half the window.

Is there a fail safe way to make sure the window will scroll to that div after the page refreshes? Again, the below does work in Firefox but only partially works in Chrome and Safari.

<script>
jQuery(document).ready(function($) {

    if(window.location.href.indexOf("?updated=") > -1) {
        var postID = window.location.href.match(/\d+$/);
       $('html, body').animate({
            scrollTop: $('#post-'+postID).offset().top
        }, 'fast');
    }
});
</script>

Also side note, not sure if this helps but once the form is submitted if I hit refresh on the page then it scrolls to the correct location.. Not sure if I should add a delay or speed up the animation to make this work cross browser like it does in FF?

Try putting the ".animate()" method inside a timeout of 2seconds. Does the problem go away? If it does, then its timing issue. Most likely thats because the browser is not ready to scroll to the location that you ask it to scroll to.

In this situation, you'd rather go with a timeout of 0 than a 2 sec. A 0 timeout just schedules the scroll for next cycle whenever the browser is free.

HTH!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM