2

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?

Derek
  • 4,747
  • 7
  • 44
  • 79
  • Can you provide more context in the form of a [jsfiddle](http://jsfiddle.net/) or similar? – cazzer Feb 25 '14 at 20:36
  • 3
    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. – Trunal Bhanse Feb 25 '14 at 20:47
  • Trunal I think that did the trick.. Can you post as answer so I can accept? – Derek Feb 25 '14 at 21:11

1 Answers1

0

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!

Trunal Bhanse
  • 1,651
  • 1
  • 17
  • 27
  • Why not use `$(document).load`? Negates any issues with a delay in loading images and you'll know for sure it will hit the right coordinates. – Papa Feb 25 '14 at 22:46