Vanilla JS change active state of links when scrolling refactoring

后端 未结 2 640
逝去的感伤
逝去的感伤 2020-12-17 06:22

I\'m trying to ditch jQuery from my upcoming projects. I found a way to create a sticky nav on scroll with pure Vanilla JS, and wanted the links on my navigation to change t

2条回答
  •  猫巷女王i
    2020-12-17 07:18

    There can be more than one ways of highlighting the Nav. One way of implementing this feature is as follow-

    We will apply "active" class to an active Nav link and add some css for this class to highlight it.

    Here are the steps how you can apply "active" class to a proper Nav link:

    STEP 1-

    Add a class to every Nav links same as the id of corresponding section while creating your Nav bar.

    For example, the Nav link corresponding to a section having id="section1" will have its class set to section1 ( i.e class="section1")

    STEP 2-

    On Scroll event in the browser, iterate through every section and check if it is in the view-port (getBoundingClientRect()) .

    If a section is in the viewport, make this as well as the corresponding Nav link active as follow-

    if (section is in the viewport) {
        // 1. Add "your-active-class" to the current section
        // 2. Add "active" class to the Nav link which have a class same as id of the current section
        } else {
         // 1. Remove "your-active-class" from the current section.
     // 2. Remove "active" class from the Nav link which have a class same as id of current section
        }
    

    STEP 3-

    In you css file, write styles for class "active" and "your-active-class" so that the Nav link and section can be highlighted using different text or background colors.

提交回复
热议问题