JQuery Scroll Spy Implementation

I have structured the page with a header at the top and 3 columns below. The left column contains a menu, the middle column is a text container, and the right column is another section.

As the page scrolls up, the menu becomes fixed in position which functions correctly.

Issue: While scrolling up, each menu should be highlighted (Scroll Spy), but only the last menu is highlighted.

Please provide assistance!

View the sample on jsfiddle

JS

$(function () {
    $(window).on('scroll', function (event) {
    var scrollValue = $(window).scrollTop();      
    if (scrollValue > 100) {
      $('#spy').addClass('affix');

      var elemts = $('.scroll-section');
      elemts.each(function(index) {
        var id = $(this).attr('id');
        console.log(id)
        var navElem = $('a[href="#' + id + '"]');
     navElem.addClass('active').parent().siblings().children().removeClass( 'active' );
      })
      } 
    else{
        $('#spy').removeClass('affix');
      }

    });          
});

CSS

.header {
  width: 100%;
  height: 100px;
  background: yellow;
}
.affix {
  position: fixed;
  top: 0;
}
#spy {
  position: fixed;
}
.right-side {
  background: gray;
  height: 120px;
}

HTML

<body>
<div class="header">

</div>
<div class="row">
<div class="col-sm-3">
<div  id="spy">
  <ul class="nav nav-pills flex-column">
    <li class="nav-item">
        <a class="nav-link" href="#scroll1">First Section</a>             </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll2">Second Section</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll3">Third Section</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll4">Fourth Section</a>
    </li>
  </ul>
  </div>
</div>
<div class="col-sm-7">
  <div class="scroll-section" id="scroll1">
    <h2>First Section</h2>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) 
    ...
    </p>
  </div>
  <div class="scroll-section" id="scroll2">
    <h2>Second Section</h2>
    <p>
    ...
    </p>
  </div>
  <div class="scroll-section" id="scroll3">
    <h2>Third Section</h2>
    <p>
    ...
    </p>
  </div>
  <div class="scroll-section" id="scroll4">
    <h2>Fourth Section</h2>
    <p>
    ...
    </p>
  </div>
</div>
<div class="col-sm-2">
  <div class="right-side">

  </div>
</div>
</div>
</body>

Answer №1

Make sure to check if the top of each section has exceeded the window's top before adding or removing the active class. Here's the code snippet with the necessary if statement:

if ( scrollValue > $(el).offset().top  ){
   var id = $(el).attr('id');
   var navElem = $('a[href="#' + id + '"]');
   navElem.addClass('active').parent().siblings().children().removeClass( 'active' );
}

Updated jsFiddle Demo

$(function () {
        $(window).on('scroll', function (event) {
            var scrollValue = $(window).scrollTop();
            if (scrollValue > 100) {
              $('#spy').addClass('affix');

              var els = $('.scroll-section');
              els.each(function(index, el) {
                if ( scrollValue > $(el).offset().top  ){
                  var id = $(el).attr('id');
                  var navElem = $('a[href="#' + id + '"]');
                  navElem.addClass('active').parent().siblings().children().removeClass( 'active' );
                }
              });
            } else {
              $('#spy').removeClass('affix');
            }
        });          
    });
.header {
  width: 100%;
  height: 100px;
  background: yellow;
}
.affix {
  position: fixed;
  top: 0;
}
#spy {
  position: fixed;
}
.right-side {
  background: gray;
  height: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

<body>
<div class="header">

</div>
<div class="row">
<div class="col-sm-3">
<div  id="spy">
  <ul class="nav nav-pills flex-column">
    <li class="nav-item">
        <a class="nav-link" href="#scroll1">First Section</a>             </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll2">Second Section</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll3">Third Section</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#scroll4">Fourth Section</a>
    </li>
  </ul>
  </div>
</div>
<div class="col-sm-7">
  <div class="scroll-section" id="scroll1">
    <h2>First Section</h2>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
  </div>
  <div class="scroll-section" id="scroll2">
    <h2>Second Section</h2>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
  </div>
  <div class="scroll-section" id="scroll3">
    <h2>Third Section</h2>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
  </div>
  <div class="scroll-section" id="scroll4">
    <h2>Fourth Section</h2>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
    <p>
    During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) are CPU-Independent set of instructions that can be effectively converted to the native code. Now with the help of JIT compiler, IL code can be executed on any computer architecture supported by the JIT compiler.
    </p>
  </div>
</div>
<div class="col-sm-2">
  <div class="right-side">
  
  </div>
</div>
</div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Superimpose a canvas onto a div element

I'm struggling to overlay a canvas on top of a div with the same dimensions, padding, and margins. Despite using position: absolute and z-index as suggested in similar questions, the canvas keeps appearing underneath the div. Here's my current co ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

Use jQuery to clear the content within a div element following the removal of an element

A dynamic generation of checkboxes is introduced to div1: $.each(json, function(idx, obj) { $("#tbl1").append('<input type="checkbox" id='+obj.firstId+' onclick=nextPopulate('+obj.firstId+'); >'); } Upon selection, ch ...

displaying the outcome of the extended project in Ajax

I am currently working with a Java class that contains various functions. Each function is responsible for printing its result either in the console or on a web page, depending on how it was initiated. The structure of my class looks something like this: ...

Utilize a CSS style or class on a div element

Looking for a way to style alternate div elements within a parent div? Check out this example: <div id="comment"> <div id="m1">...</div> <div id="m2">...</div> </div> I tried to use some jQuery to add a CSS c ...

How come the element is not appearing in the div even though it should be there?

The placement of the image and select menu within the same div element may be causing a display issue where only the first image is shown correctly and the select menu appears outside. Why does this occur? <body> <div style="height: 1080px; ...

I am looking to implement a Mouseover effect on my Canvas element using JavaScript

To create a mouseover effect only on a specific canvas location, I have developed the MousePosition function (as seen below). The commands for the mouseover effect should be implemented within the MouseOverButton function. However, despite my efforts, it ...

The React modal refuses to disappear, stubbornly clinging to the original component it sprang from

Hey there, I'm a beginner in learning React and I'm encountering an issue with my popup modal component. Even after showing the modal, I can still interact with and click on the main UI elements. Can anyone assist me with this problem? https://i ...

Enhance click functionality on list item content using knockoutjs

Check out my app on GitHub or view it live at this link. I'm trying to implement a feature where clicking on each item, like "Bookworm Buddy," will toggle its description within the project. Here's what I've attempted so far: function AppV ...

Tips for invoking a .aspx document within a .ascx file using json and ajax technology

Currently in the process of developing a large website using ASP.net and either vb.net or C#, I am facing a challenge where upon clicking a button, specific text should be displayed on the site. To achieve this, I plan to utilize ajax/json to call a .aspx ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

Tips for replacing the values obtained during parsing an XML document

I am working with an XML file that contains category and product information. Here is a snippet of the XML data: <categories> <category id="2" name="Pepsi" > <products> <product id="858" name="7UP" price="24.4900" /> ...

`Updating table values using jQuery`

I've designed an app for a virtual bowling game where players can see their scores updated in real-time. However, there's a glitch in the system - the scores won't display on the screen until the page is refreshed. If anyone out there has a ...

Decipher the JSON data for a Facebook cover photo

I am utilizing the Facebook Graph API to retrieve the user's cover picture. By accessing the link provided at , a JSON object containing the picture link is returned. How can I fetch this link using JQuery or JavaScript? Here is my attempt: HTML: & ...

Having trouble with generating HTML templates with inline CSS in Flask

How can I randomly select a background picture (out of 4) for my homepage on a personal website using Flask? Despite my attempts to create an HTML template with inline CSS, the selected image does not display as expected. I've already tried using url ...

Combining multiple events in jQuery to trigger a single Ajax function

What is the best way to optimize two jQuery events that use the same ajax function? $(document).on("focus blur change keyup", "#bc", function () { $.ajax({ XXXXXXXXXXXXXX }); }); $(document).on("change", ".op", function () { $.ajax({ ...

What is the recommended approach for displaying data enclosed in double quotes in PHP?

Looking to store HTML text in a variable without using ?> .... <?. The challenge lies with the quotes — wanting to have double quotes instead of single quotes. Using single quotes for variables with interpolation doesn't work: $var = ' ...

The process of transferring information from JSON to Java

I need help converting the start date from a JSON object to Java in my JSP page. The AJAX call is returning the date as 153452636268, but I want it in a different format. Can someone please provide assistance? $.ajax({ type: "GET", url: ...

Unable to access the website's source code

It's frustrating when I can't view the source code of certain websites, such as this one: . When I try to right-click and select "View Source", only a portion of the code is displayed, which isn't the proper source code for the page. Alth ...

Retrieve the nearest identifier text from the tables

I have a table on my webpage with some data: <tbody id="carga"> <tr> <td>1</td> <td id="nombre">esteban</td> <td id="apellido">aguirre</td> <td>N/A</td> <td>N/A</td ...