Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scroll to y position

Tags:

javascript

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>

like image 343
Lukáš Ježek Avatar asked Aug 16 '26 11:08

Lukáš Ježek


2 Answers

You 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>
like image 93
Johan Avatar answered Aug 18 '26 00:08

Johan


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.org/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>
like image 25
kundan Karn Avatar answered Aug 18 '26 01:08

kundan Karn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!