Search code examples
javascriptjqueryhtmlbootstrap-4intersection-observer

How to make automatic navbar based on section of a webpage?


I come across two cases where the navigation bar items are selected automatically when I scroll to certain section. How do I achieve that? I'm looking for a solution which is up to date of 2018 and as simple as possible(vanilla JS or without extra JS using bootstrap). I found several post about using jquery to do that but looks like intersection observer is a better approach?

One example is https://insights.stackoverflow.com/survey/2018/, another is http://getbootstrap.com/docs/3.3/javascript/#dropdowns.

Let's assume I have following html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">
    <link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="navbar">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active" id="about-nav-item">
                    <a class="nav-link" href="#about">About <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item" id="portfolio-nav-item">
                    <a class="nav-link" href="#portfolio">Portfolio</a>
                </li>
                <li class="nav-item" id="contact-nav-item">
                    <a class="nav-link" href="#contact">Contact</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container" id='about'>
    </div>
    <div class="container" id='portfolio'>
    </div>
    <div class="container" id='contact'>
    </div>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
    <script type="text/javascript" src="code.js"></script>
</body>

</html>


Solution

  • where the navigation bar items are selected automatically when I scroll to certain section. How do I achieve that?

    This component is called "scrollspy" in Bootstrap 4.

    From the docs:

    Automatically update Bootstrap navigation or list group components based on scroll position to indicate which link is currently active in the viewport.

    Reference:

    https://getbootstrap.com/docs/4.0/components/scrollspy/