JavaScript Answers

How to fix anchor jumping by using JavaScript?

Spread the love

Anchor jumping, also known as page scrolling to an anchor point when clicking on a link, can be prevented using JavaScript.

To do this, we write:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Anchor Jumping</title>
  /* Style for the anchor links */
  .anchor-link {
    display: block;
    margin-bottom: 20px;

<!-- Example anchor links -->
<a href="#section1" class="anchor-link">Go to Section 1</a>
<a href="#section2" class="anchor-link">Go to Section 2</a>

<!-- Example sections with ids -->
<div id="section1" style="height: 1000px; background-color: lightblue;">
  <h2>Section 1</h2>

<div id="section2" style="height: 1000px; background-color: lightgreen;">
  <h2>Section 2</h2>

// Prevent default anchor behavior and handle scrolling with JavaScript
document.addEventListener('DOMContentLoaded', function() {
  const anchorLinks = document.querySelectorAll('.anchor-link');

  anchorLinks.forEach(function(link) {
    link.addEventListener('click', function(event) {
      event.preventDefault(); // Prevent the default anchor behavior

      const targetId = this.getAttribute('href').substring(1); // Get the id of the target section
      const targetSection = document.getElementById(targetId); // Find the target section

      if (targetSection) {
        const yOffset = targetSection.getBoundingClientRect().top + window.pageYOffset; // Calculate the target offset
        window.scrollTo({ top: yOffset, behavior: 'smooth' }); // Scroll to the target with smooth behavior

In this example, anchor links are created with the href attribute pointing to the corresponding section IDs.

The default behavior of anchor links is prevented using JavaScript by calling preventDefault() in the event listener attached to each anchor link.

When an anchor link is clicked, JavaScript calculates the target section’s offset from the top of the page using getBoundingClientRect() and window.pageYOffset, and then scrolls to that offset with smooth behavior using window.scrollTo().

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *