does anybody know why scrolling of scrollbar to y position does not work? Very simple code below. In JSFiddle it works fine. I don't see any reason why it should not work. Scroll bar appears but still at the top :-(
<script>
window.scrollTo(50,100);
</script>
<body>
<div style="width:200px; height:1500px;background-color:blue;">
hello
</div>
</body>
does anybody know why scrolling of scrollbar to y position does not work? Very simple code below. In JSFiddle it works fine. I don't see any reason why it should not work. Scroll bar appears but still at the top :-(
<script>
window.scrollTo(50,100);
</script>
<body>
<div style="width:200px; height:1500px;background-color:blue;">
hello
</div>
</body>
Share
Improve this question
asked Nov 15, 2013 at 7:53
Lukáš JežekLukáš Ježek
751 gold badge3 silver badges12 bronze badges
2
-
1
Have you tried putting the
<script>
element at the bottom of the page, before the end of<body>
? – J. Holmes Commented Nov 15, 2013 at 7:57 - Your script is executed before the DOM is loaded. – Derek 朕會功夫 Commented Nov 15, 2013 at 8:34
2 Answers
Reset to default 4You need to put the script block below the div and attach the scrollTo to the windows onload event for this to scroll down on page load.
Try this:
<body>
<div id="div1" style="width:200px; height:1500px;background-color:blue;">
hello
</div>
<script>
window.onload = function() { window.scrollTo(50,100); };
</script>
</body>
Script must be executed after all DOM elements are created so use window.onload method for javascript and $(document).ready() for jQuery
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function () {
window.scrollTo(50, 100);
}
</script>
</head>
<body>
<div style="width:200px; height:1500px;background-color:blue;">
hello
</div>
</body>
</html>