Highlight Active Links

How to Highlight Active Navigation Links with Vanilla JavaScript

html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./main.js" defer></script>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body>
    <nav id="nav">
        <a href="#page01">page 01</a>
        <a href="#page02">page 02</a>
        <a href="#page03">page 03</a>
        <a href="#page04">page 04</a>
        <a href="#page05">page 05</a>

        <a href="#page06">page 06</a>
        <a href="#page07">page 07</a>
        <a href="#page08">page 08</a>
        <a href="#page09">page 09</a>
        <a href="#page10">page 10</a>

        <a href="#page11">page 11</a>
        <a href="#page12">page 12</a>
        <a href="#page13">page 13</a>
        <a href="#page14">page 14</a>
        <a href="#page15">page 15</a>

        <a href="#page16">page 16</a>
        <a href="#page17">page 17</a>
        <a href="#page18">page 18</a>
        <a href="#page19">page 19</a>
        <a href="#page20">page 20</a>
    </nav>
</body>

</html>

css

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    text-decoration: none;
    color: #111;
}

nav {
    width: 250px;
    height: 100vh;
    display: flex;
    overflow: auto;
    flex-direction: column;
    justify-content: start;
    align-items: start;
    background-color: #fdfdfd;

    & a {
        width: 100%;
        padding: 15px 10px;
    }

    & .active-page {
        background-color: #b7e4ff;
    }
}

javascript

const links = document.querySelectorAll('#nav a');
const nav = document.getElementById('nav');
nav.addEventListener('click', (e) => {
    const targetEl = e.target.closest('a');
    if (targetEl) {
        links.forEach(link => {
            link.classList.remove('active-page');
        });
        targetEl.classList.add('active-page');
    }
});

for (let i = 0; i < links.length; i++) {
    if (links[i].href == window.location.href) {
        links[i].classList.add('active-page');
    }
};

const activeElement = document.querySelector('.active-page');
activeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });