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

Utilize the CakePHP form helper to include an HTML element within a form element

I am attempting to generate a basic html output that resembles the following <button class="searchbutton" id="search_button" type="submit">--> <i class="icon-search"></i> Search</button> when using Cake PHP's form h ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

Struggling with Jquery Ajax - unable to achieve success, only encountering errors

Is there anyone who could help me with why each ajax call seems to be resulting in an error? Let me elaborate on my issue. Here is the code snippet: $(document).ready(function(){ $('#officer-id').change(function(){ var officer_id = $(' ...

Comparing strings with Ajax

I have been working on a basic ajax function setInterval(function() { var action = ''; var status = ''; $('#php-data').load('../Data/Dashboard.Data.php'); $.ajax({type: 'POST', u ...

No styles are appearing on a specific element after running a specific jQuery function on that element within a Vue page

I recently integrated JQuery-AsRange (https://github.com/thecreation/jquery-asRange) into my vue.js project. Everything functions as expected within the .vue page, however, I am facing an issue with css styling not being applied. The css styles should be ...

JavaScript code that triggers a page refresh when an input is added to a form without actually inputting

Upon delving into extensive research on this particular subject, I regrettably came up empty-handed. My sincere apologies if this question has been posed before. The task at hand involves creating a form that prompts users to input information about four ...

A cookie designed to store and retain the preferred CSS stylesheet choice

I'm looking to create a cookie that will store the preference for a specific CSS stylesheet. I currently have a function in place that allows me to switch between stylesheets: function swapStylesheet(sheet){ document.getElementById('pagestyl ...

Customizing Material UI: Grouping Tab components within a div container

How can I wrap the children of a Material UI Tabs component in divs? <Tabs value={value} indicatorColor="primary" textColor="primary" onChange={handleChange} > <div> <Tab label="x" /> ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

What steps can I take to stop a select box within a flex container from shrinking?

Currently working on some code that involves a flex container. Struggling to prevent fields from shrinking too much on smaller screen sizes. var crsdesc; //var for new window function popup(mylink) { if (!window.focus) return true; var href; if (t ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

Leveraging personalized data-* attributes within the <template> tag in HTML5

I am currently developing a menu using a dom-repeat template as shown below: <template is="dom-repeat" items="{{appletsMenu}}"> <a data-route="{{item.dataRoute}}" href="{{item.href}}"> <iron-icon icon=" ...

What is the process for locating and displaying a database in WordPress?

I seem to be facing a challenge when it comes to developing a new functionality since I am relatively new to both WordPress and web development. My current goal is to incorporate a search feature into my project. The idea is that when a user enters a sea ...

The functionality of Bootstrap tooltips becomes disabled as soon as any element on the page is clicked

When initializing Bootstrap tooltips on my page, I follow this approach <script> $(document).ready(function () { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }); </script> A questio ...

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click. <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button> <select id="quantity1" class="ml- ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...