Smooth Scrolling to Anchor Using JavaScript
Last updated: 09.10.2025
Views: 217
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:
-
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 ...
-
How to Make Asynchronous Requests in a Loop in JavaScript
Implementing asynchronous requests inside a JavaScript loop may not seem obvious at first. When making asynchronous requests inside a JavaScript loop, it is important to ...
-
How to Create a Custom jQuery Plugin
The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you ...
Leave a Reply