9

I use:

var el = document.getElementById("centd");
el.scrollIntoView(true);

to scroll to specific position. In every browser it works fine, but in Chrome when the page is loaded it scrolls to that point, but after a second or two (when the page is finished loading) it scrolls back to start.

Satyam Koyani
  • 4,236
  • 2
  • 22
  • 48
Dim
  • 4,527
  • 15
  • 80
  • 139
  • You can use this plugin: http://erraticdev.blogspot.com.ar/2011/02/jquery-scroll-into-view-plugin-with.html because of this: http://stackoverflow.com/questions/9445842/does-scrollintoview-work-in-all-browsers?lq=1 – pablofiumara Oct 01 '13 at 08:47
  • Are you doing that eg. in DOMContentLoaded event, not directly? – Samuli Hakoniemi Oct 01 '13 at 08:54

2 Answers2

6

Make sure all your JavaScript code is run after your page completes loading:

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

Or if you're using jQuery:

$(document).ready(function(){
// your code
});

This will make sure that your code runs the way you intend.

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
0

I feel like it's supposed to be a feature and not a bug (but cannot find evidence to support this theory): it works fine the first time the page loads / in a new tab, but as soon as the user scrolled, that scroll-position overrides any scrollTo or scrollIntoView commands (in this briefly flashing fashion you described, and that I am currently trying to make sense of) – even if you wait for the document to be ready.

Other browsers don't share this behavior, in my experience.

WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25