8

When I visit my_site.com/page.php#something, the scroll position is the one of the element carrying this particular hashtag rather than the top of the page.

Executing window.scrollTo(0, 0); doesn't change this fact. What can then?

EDIT: also tried accepted answer from How to disable anchor "jump" when loading a page?. Doesn't seem to work anymore.

Community
  • 1
  • 1
drake035
  • 3,955
  • 41
  • 119
  • 229
  • Possible duplicate of [How to disable anchor "jump" when loading a page?](https://stackoverflow.com/questions/3659072/how-to-disable-anchor-jump-when-loading-a-page) – Jake Reece May 01 '19 at 15:39

2 Answers2

16

What you have to do is store the hashtag for later use and then delete it so that the browser doesn't have anything to scroll to.

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be to late and the browser already have moved to the tag.

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).load(function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});
Larzan
  • 9,389
  • 3
  • 42
  • 41
  • 1
    i had ran into a bug with FF where I was using max-height overflow-y on a div with a really long list, FFwould scroll down where the hidden node would be in the dom. This only used the top three lines of actual code (not the comments) and this corrected my issue with FireFox. – JQII Aug 24 '16 at 18:44
5

Having this HTML code:

<a href="#test">link</a>
<div id="test"></div>

You can avoid scrolling to the div element and instead scrolling to the top of the window by using this code:

$("a").on("click", function(e) {
    e.preventDefault();
    window.scrollTo(0, 0);
});

EDIT:

You can try to add this:

var firstVisit = true;
$(window).scroll(function() {
    if (firstVisit) {
        window.scrollTo(0, 0);
        firstVisit = false;
    }
});
Dim13i
  • 1,961
  • 1
  • 17
  • 20
  • 2
    Thanks but the problem is not when I click on anything, rather when I "visit" the page. – drake035 Nov 24 '14 at 01:43
  • @drake035 I've edited the answer. Don't know if it is the most efficient, or best way, but it seems to work. – Dim13i Nov 24 '14 at 01:55
  • 1
    Just edited the answer because there was a typo in the **if** condition in the scroll function. Try again if you can. – Dim13i Nov 25 '14 at 13:53