rwx rwx - 5 months ago 19
HTML Question

Chrome doesn't always jump to #top while Firefox is doing fine

Site description



I have a page where a list of 10
div
are showing at once while 100 are in the source document. On the bottom is a button that - if clicked - hides these 10
div
and shows the next 10
div
. The button itself is a styled link with
href="#top"
where the id belongs to my
navbar
on top.

Problem



If I use Chrome it doesn't jump to top every time I click on the button. Sometime it jumps and sometimes it just show the new divs without the jump to top.

What works



If I use Firefox there's no problem.

Question



How can I figure out where's the problem - I mean, could there be an error somewhere else in my code that leads to this behaviour (no jump to
#top
) - or is there an alternative way to tell the users browser to jump to top that I should or could use?

Answer

Instead of using anchors and links to them (because your anchors might change positions, or work different between browsers), you should use Javascript, using the window.scrollTo() function:

HTML

<button onclick="scrollToTop()">Go to Top</button>

Javascript

function scrollToTop(){
    window.scrollTo(0, 0);
}

Note that scrollTo() takes two parameters; the top and left position to scroll to. Also scrollTo() is not animated, it will scroll instantly to the position that you set.