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);
});
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);
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);
}
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly