smooth scroll js code example
Example 1: 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 2: smooth scroll css
html {
scroll-behavior: smooth;
}
http://iamdustan.com/smoothscroll/
Example 3: how to smooth scroll in javascript
window.scrollTo({ top: 900, behavior: 'smooth' })
Example 4: javascript scroll down
window.scrollTo(300, 500);
Example 5: smooth scroll to id
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});
Example 6: smooth scroll
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100,
left: 0,
behavior: 'smooth'
});
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});