Smooth Scrolling to Anchor Using JavaScript
Last updated: 09.10.2025
Views: 218
Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smooth scrolling creates a fluid motion, making transitions more visually appealing. In this article, we’ll explore how to implement smooth scrolling using JavaScript. It’s not difficult at all to implement this. Let’s dive in and make your website navigation feel effortless!
HTML
<ul class="nav-block"> <li><a href="#first">First block</a></li> <li><a href="#second">Second block</a></li> <li><a href="#third">Third block</a></li> <li><a href="#fourth">Fourth block</a></li> </ul>
The id attribute is used to designate an anchor. For example:
<div id="first"> Some your content... </div>
JavaScript
const els = document.querySelectorAll('.nav-block a');
els.forEach((el) => {
el.addEventListener('click', (ev) => {
ev.preventDefault();
const id = el.getAttribute('href').slice(1);
const block = document.getElementById(id);
if (block) {
window.scrollTo({
top: block.offsetTop,
behavior: 'smooth',
});
}
});
});
If you use jQuery in your project, then you can write almost the same thing using this JavaScript library.
jQuery
$('.nav-block a').on('click', function(ev) {
ev.preventDefault();
const id = $(this).attr('href');
const top = $(id).offset().top;
$('body,html').stop().animate({scrollTop: top}, 1000);
});
1000 – scroll time in milliseconds
Similar posts:
-
Vue Accordion Component
A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
-
Working with Cookies in JavaScript
Сookie (web cookie or browser cookie) is a string of information that can be stored in a browser and sent to the server. The maximum size for one cookie is 4096 bytes. T...
-
How to Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to determine the user's operating system. To use different CSS styles for different OS, or for some analytics, or for other purposes. There are ...
Leave a Reply