jquery scroll to section code example
Example 1: smooth scroll jquery onclick
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
Example 2: scroll to element jquery
$('html, body').animate({
scrollTop: $("#grepperRocks").offset().top
});
Example 3: jquery scroll to element
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
Example 4: smooth scrolll to id js
$(document).on('click', 'a[href^="#"]', function(e) {
var id = $(this).attr('href');
var $id = $(id);
if ($id.length === 0) {
return;
}
e.preventDefault();
var pos = $id.offset().top;
$('body, html').animate({scrollTop: pos});
});
Example 5: how to add scroll to div onclick
<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>