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







3 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);

2
At:- 6/9/2017 12:09:24 PM Updated at:- 12/9/2022 6:59:27 AM
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

document.getElementById("DivId").scrollIntoView();

But yes, this will not be smooth scroll.

For Smooth Scroll Using Pure Javascript (without jQuery)

// scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

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);
}
1
At:- 3/27/2021 6:49:56 AM
Thanks, for Pure Javascript based smooth scroll solution 0
By : vikas_jk - at :- 6/8/2022 7:04:32 AM


profileImage Answered by:- Vinnu

Scroll to div using Plain javascript (js) using below code:

document.getElementById("someElementId").scrollIntoView({ behavior: "smooth" });

Note: Safari on iOS doesn't support this, rest other major browsers support it.

0
At:- 12/9/2022 3:41:09 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