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:
-
Countdown Timer in JavaScript
Countdown timers are commonly used on websites that promote products, services, or special offers. You can often see them on landing pages or in online stores, where they...
-
Ways to Create Objects in JavaScript
There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain ot...
-
How to Сlone (Copy) Object and Array in JavaScript
Cloning objects and arrays is not as simple a topic as it may seem at first glance. Cloning objects and arrays in JavaScript can be done using various methods depending...
Leave a Reply