Scroll to another div on button click in Javascript

We can scroll to another div using window.scrollBy() .The window.scrollBy() method scrolls the document by the specified number of pixels. 

Syntax :Function can be used in following ways

1.window.scrollBy(x-coord, y-coord) 

x-coord : Required. 
Number of pixels to scroll (horizontally). 
Positive values scroll to the right, negative values to the left. 
window.scrollBy(options) 

y-coord : Required. 
Number ofpixels to scroll (vertically). 
Positive values scroll down, negative values scroll up. 

2. scrollBy(options) 

options 

A dictionary containing the following parameters: 

top : Specifies the number of pixels along the Y axis to scroll the window or element. 

left : Specifies the number of pixels along the X axis to scroll the window or element. 

behavior :Specifies whether the scrolling should animate smoothly (smooth), happen instantly in a single jump (instant), or let the browser choose (auto, default). 

In the given example, we use top parameter.In the example,offsetTop of the div to be scrolled is passed as the value to window.scrollBy() function.So on click of the button,page will scroll to the content div 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .mainDiv{
        background-color: beige;
        height: 1500px;
        width: 1500px;
    }
    .innerDiv{
        background-color: lightblue;
        position: relative;
        top:800px;
        height: 200px;
        width: 200px;
    }
</style>
<body>
    <div class="mainDiv">
        <button class="btnScroll" onclick="scrollToContent();">Scroll to Content</button>
        <div class="innerDiv">
            <h1 class="contentH1">
                Heading
            </h1>
            <p>
                This is an example for window.scrollBy
            </p>
        </div>
    </div>
</body>
<script>
    function scrollToContent(){
        window.scrollBy({
                

                top: document.querySelector('.innerDiv').offsetTop,
                behavior: "smooth"
            });
    }
</script>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *