jquery smooth scroll to anchor code example
Example 1: smooth scroll jquery onclick
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
Example 2: javascript smooth scroll to anchor element
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Example 3: smooth scroll to id
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100,
left: 0,
behavior: 'smooth'
});
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});