To implement smooth scrolling to anchor links on a webpage using JavaScript, you can follow these steps:
event.preventDefault()
.document.querySelector(target)
, where target
is the value of the href
attribute of the anchor link (including the #
symbol).window.scrollTo()
method to smoothly scroll to the target element. You can pass the target element position and some additional options like behavior: 'smooth'
to create a smooth scrolling effect.Here's an example implementation:
// Get all anchor links on the webpage
const anchorLinks = document.querySelectorAll('a[href^="#"]');
// Attach click event listener to all anchor links
anchorLinks.forEach(anchorLink => {
anchorLink.addEventListener('click', smoothScroll);
});
// Event handler for smooth scrolling
function smoothScroll(event) {
// Prevent default anchor link behavior
event.preventDefault();
// Get the target element
const target = document.querySelector(this.getAttribute('href'));
// Calculate the scroll distance
const scrollDistance = target.offsetTop - window.pageYOffset;
// Scroll smoothly to the target element
window.scrollTo({
top: target.offsetTop,
behavior: 'smooth'
});
}
By adding this JavaScript code to your webpage, all anchor links with href
attribute starting with #
will scroll smoothly to their target elements.