how to scroll to div smoothly on click using jquery

I want to scroll to a div on button using jquery, which is working, but as a i was expecting, what i need here to scroll to div smothly(with animation), but it is jumping to a div directly(no animation or smotth scroll) on button click, my jquery code is

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);

Asked by:- Vinnu
: 1756 At:- 6/9/2017 7:32:27 AM
jquery scroll javascript

2 Answers
profileImage Answered by:- vikas_jk

Hello, thanks for asking a question

You need to animate the HTML, body, also there is no .scrollTo() method in jQuery, but there is a .scrollTop() one. .scrollTop expects a parameter, that is, the pixel value where the scrollbar should scroll to, so your code will be

$("#button").click(function() {
//animate html body and use jQuery scrollTop
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);

that's it, it should resolve your issue.

Or you can have another alternative  method to use it many times

  scrollTo : function(speed, easing)
    return this.each(function()
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);

Use it like $('div').scrollTo(500);

At:- 6/9/2017 12:09:24 PM
very well, thank you, I have asked another question, please answer it if possible 0
By : Vinnu - at :- 6/9/2017 4:50:56 PM

profileImage Answered by:- bhanu

You can also do it without using jQuery, using Pure JS


But yes, this will not be smooth scroll.

Using jQuery Smooth scroll, if a "#" is found in URL, below script will scroll to that element Id after "#" in url.

if($(window.location.hash).length > 0){
      $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
At:- 3/27/2021 6:49:56 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use