Smooth Scrolling to Anchor Using JavaScript
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 transition, making interactions feel more natural and visually appealing.
This technique is especially common on landing pages, where navigation links often point to different sections of the same page. Smooth scrolling helps guide the user through content in a more engaging way, improving readability and overall usability. It is frequently used in menus, “scroll to top” buttons, and anchor links within long pages.
From a technical perspective, implementing smooth scrolling with JavaScript is quite straightforward. Modern browsers already provide built-in support for smooth scrolling behavior, which means you can achieve the effect with minimal code. At the same time, you can customize the scrolling logic if you need more control over speed, offset, or animation.
In this article, we will look at a simple way to implement smooth scrolling using JavaScript, making your website navigation feel clean and 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 Get Max Value in JavaScript Array
A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. To find the maximum va...
-
Swipe Events on Touch Devices in JavaScript
Every day sensory devices are being introduced into our lives. These devices have specific events, unlike the desktop. One of these events is the swipe. Especially often ...
-
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...
Leave a Reply