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
1
: 215 At:- 6/9/2017 7:32:27 AM
jquery scroll javascript






1 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

jQuery.fn.extend(
{
  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);

1
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





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

Full Name *

Email *




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