I'm converting this jQuery code:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html,body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
});
It's very popular, and I'm sure everyone understand what it does, when clicking an anchor link with an id it smooth scrolls to it. I have used this code for many projects but I am no longer using jQuery, as it is being deprecated. Converting this to vanilla JavaScript has proven a challenge. This is what I have so far, that works:
document.addEventListener('click', function(event) {
if (event.target.matches('a[href^="#"')) {
event.preventDefault();
console.log('works fine')
}
}, false);
I am having trouble finding resources to convert .animate() and the line with scrollTop
. It's a pretty tall order for someone with only beginner/intermediate JS experience. I was wondering if anyone knew how to convert this code to JavaScript, or where I could find resources about converting this. A popular solution to smooth scrolling I have found is the following code:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Using scroll-behavior: smooth
, but I do not wish to use this as it is unsupported by many browsers (to my knowledge), and it does not let me customize how long it takes to smooth scroll.
Any help would be much appreciated.