Setting the scrollbar position of a block element in HTML

32 views Asked by At

I want to set the scrollbar position of a block to specific coordinates when the page is loaded.

The closest thing I found to this is the

window.scrollTo

method in JavaScript, which sets the scrollbar positions of the horizontal and vertical scrollbars of the whole page in the browser. This script can then be run when the page is loaded.

I want to do the same with a block like this:

<div>
    <p> lots of text </p>
<div>
<style>
    div {
        overflow: scroll;  
}
</style>
1

There are 1 answers

0
Joshua George On

You can use the scrollTop and scrollLeft properties of scroll to do this.

<style>
    .scrollable {
        width: 200px;
        height: 200px;
        overflow: auto;
        border: 1px solid #ccc;
    }
</style>

<script>
    window.onload = function() { 
        //runs on page load
        // Set the desired scroll position x,y
        var x = 0; // Horizontal scroll position
        var y = 100; // Vertical scroll position
        
        // Get the scrollable block
        var block = document.getElementById("scrollableBlock");
        
        // Set the scroll positions ez
        block.scrollLeft = x;
        block.scrollTop = y;
    };
</script>