Reload page; anchor link is ignored and preference is given to the previous scroll position?

It puzzles me, and I'm afraid that I can do something very stupid.

I have a form that makes an ajax call and, if successful, reloads the (same) page and goes to the presented data at the bottom of the page using the hash / URL fragments.

window.location.href = "/this/url/#post-10";
window.location.reload();

...

<div id="post-10">...</div>

I noticed that, at least with Chrome, the previous scroll position is preferable to the binding that I provide - so reloading the page successfully goes to my anchor id, but as soon as the page finishes loading, it jumps to the scroll point on the previous page.

Is this standard behavior? Is the best approach to fix this to simply force the page position to use onLoador something similar?

+3
source share
2 answers

window.location.href = "/this/url/#post-10"; will work on its own, there is no need to reload the page a second time, which (as far as I know) will contribute to the previous scroll position.

+2
source

If you are using ajax, why reload the page?

Just delete the line window.location.reload();

window.location.href = "/this/url/#post-10";enough to scroll to this part post-10.

By the way, the best (cool) approach would be to use the scroll effect.

var targetOffset = $('#post-10').offset().top ;
var scrollElem = scrollableElement('html', 'body');

$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
    // scroll is complete
      location.hash = 'post-10';
});

   // Use the first element that is "scrollable"  (cross-browser fix?)
function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
        var el = arguments[i],
        $scrollElement = $(el);
        if ($scrollElement.scrollTop()> 0) {
            return el;
        } else {
            $scrollElement.scrollTop(1);
            var isScrollable = $scrollElement.scrollTop()> 0;
            $scrollElement.scrollTop(0);
            if (isScrollable) {
                return el;
            }
        }
    }
    return [];
}
+1
source

All Articles