How to make scroll to an element with jQuery?

Member

by jennifer , in category: JavaScript , 2 years ago

How to make scroll to an element with jQuery?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@jennifer You can use code as example below to make a scroll to an element with jQuery. As a solution you can use scrollTop() function and pass offset from top of window.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<html>
<head>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-2.0.1.js"></script>
    <style>
        #section1,
        #section2 {
            height: 1500px;
            width: 100px;
        }

        #section1 {
            background-color: #ff2b2a;
        }

        #section2 {
            background-color: #d4e157;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <button class="go-to-div" data-id="section1">Go to div1</button>
    <button class="go-to-div" data-id="section2">Go to div2</button>
    <div id="section1">
        Test 1
    </div>
    <br/>
    <div id="section2">
        Test 2
    </div>
</div>
</body>
<script>
    $('.go-to-div').on('click', function () {
        let id = $(this).data('id');
        $(document.body).animate({
            scrollTop: $(`#${id}`).offset().top
        }, 1000);
    });
</script>
</html>

Member

by gina , a year ago

@jennifer 

You can use the scrollTop() method in jQuery to scroll to a specific element. First, you need to get a reference to the element using a selector, then set the scrollTop property to the distance of the element from the top of the page. Here is an example:

1
2
3
$('html, body').animate({
    scrollTop: $("#elementId").offset().top
}, 2000);


This will animate the scroll over 2 seconds (2000 milliseconds) to the element with the ID of "elementId". You can also use the .scrollTop property to set the position of the scrollbar, like this:

1
$("html, body").scrollTop( $("#elementId").offset().top );


It will also scroll to the element with the ID of "elementId" but it will do it without animation.