Avoid applying the active class to specific elements while scrolling

I encountered the following issue:

While trying to add logic to apply the active class on list elements in my navigation bar as I scroll, I utilized this code snippet:

$(window).bind('scroll', function () {
  var scrollPos = $(window).scrollTop() + 100;
  $('#nav-menu a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    currLink = currLink.parent();
    if (refElement.position().top <= scrollPos) { 
      $('.nav > li').removeClass("active");
      currLink.addClass("active");
    } else {
      currLink.removeClass("active");
    }
  });
});

Everything works correctly while scrolling and even when clicking on a link within the navigation bar. However, a problem arises when I have 5 links that correspond to different div sections. For example, if I am at the top of the page and click on the last link, the intermediate links also get the active class as I scroll through the content.

Is there a workaround to avoid assigning the active class to the links in between?

EDIT: Here is the code for click-to-scroll functionality:

// Page scroll
$('a.page-scroll').click(function () {
  $(".nav > li").removeClass("active");

  if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
      location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top - 40
      }, 900);
      return false;
    }
  }
});

Answer №1

Altered the code based on my previous comment regarding your question. Please confirm if this update is functioning correctly. I have annotated the changes so you can easily search for --CapitalQ.

$(window).bind('scroll', function () {
    var scrollPos = $(window).scrollTop() + 100;
    $('#nav-menu a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        currLink = currLink.parent();
        if (refElement.position().top <= scrollPos) {
            $('.nav > li').removeClass("active");

            // included a condition to add "active" only when body is not scrolling --CapitalQ
            if (!$('body').hasClass('scrolling')) {
                currLink.addClass("active");
            }
        }
        else {
            currLink.removeClass("active");
        }
    });
});

$('a.page-scroll').click(function () {

    // Assign scrolling class to body --CapitalQ
    $('body').addClass('scrolling');

    $(".nav > li").removeClass("active");
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top - 40
            }, 900, function () {

                // added callback to jQ animate function --CapitalQ
                $('body').removeClass('scrolling');
                $(this).parent().addClass('active');
            });

            return false;
        }
    }
});

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

Resolving Ion Auth's Ajax Login Redirect Problem in CodeIgniter

Trying to incorporate the Ion Auth framework into my CodeIgniter application has been a bit challenging. When a user clicks on a link, the request is sent to a Controller method to check if the user is logged in or not. If not, it redirects to the auth&bso ...

The input type "time" is failing to send the data in the expected format when using React MUI

My textfield uses type="time" and accepts input in "hh:mm AM/PM" format, but only sends the value in "hh:mm" format. Here is where you can check it out https://i.sstatic.net/wkw0D.png Is there a way to send input in the same format that the user typed i ...

Cleanse the email using express-validator, but only if it is recognized as an email format; otherwise, disregard

Currently, I am developing an API that requires users to input their username and password for authentication purposes (login functionality). Users have the option to enter their email, username, or mobile number. To ensure consistency, I need to normalize ...

Node.js is not accurately setting the content length. How can I resolve this issue?

I could use some assistance. Even though I have set the content-length on the response object, it doesn't seem to be working. Have I done something incorrectly? res.set({ 'Content-Type': res._data.ContentType, 'Content-Length' ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

There is an issue with Nuxt 3 layers not functioning properly when trying to access a project page from a different

Is there a way to make a project function independently while still being accessible through layers and able to run smoothly? The current project structure is as follows: ...

Showing Stationary Pictures at Full Size in OpenLayers

I am trying to showcase static images as maps using a StaticImage layer in ol3, with the image size set at 100% in pixels. However, I am facing difficulty in ensuring that the displayed images are always the correct size based on the extent and zoom variab ...

Searching for elements in Selenium using Python without a specified name

Looking for some assistance here. I'm trying to use Selenium to access a search field, but it doesn't have a name or ID in the html code. How can I locate and interact with this search field using Selenium? View the HTML code snippet for the sea ...

Using three.js to integrate an image onto the ground within a panorama

I need help with adding a small image (256x256) to the floor of the Panorama code I am using. Can anyone provide guidance on how to accomplish this task? ...

Challenge with implementing custom http headers in jQuery's $.ajax请求

I need help with querying a REST webservice that requires custom http headers for authentication. When I make a POST request without the headers, I get the expected error. However, when I include the headers, I receive a 404 error instead of the desired r ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Encountering a type error while executing ajax script in django

Currently, I am facing an issue with using jquery ajax to fetch json data on my webpage within the Django framework. Despite my efforts, I am unable to render the json data successfully. When attempting a simple console.log(data) as my initial step, nothin ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

I am struggling to get my card content to align perfectly in bootstrap 5

I'm having trouble centering all the content in my cards, as it keeps aligning to the right side Here is my card code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="wid ...

Troubleshooting email delivery issues with contact form submissions in PHP

Can anyone assist me in identifying where I'm going wrong with this? Every time I click 'send', the form just directs to the PHP code. I've been experimenting with it for hours and I feel like I must be overlooking something simple. I&a ...

How come (23 == true) is incorrect but (!!23 == true) is correct? After all, there is === for exact comparisons

The question boils down to this: are both 23 and true truthy values? If so, shouldn't they be equal under the loose comparison operator ==? However, there is also the strict comparison operator === for cases where precise equality is required. UPDATE ...

Is it possible to translate the content of the page into English and French simply by clicking on the designated buttons?

As I dive into working with knockout, I am still in the learning process. Currently, I have a dropdown code where selecting English translates the entire page to English and selecting French translates it to French without any issue. I believe this functio ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

"Utilize a pre-defined parameter in a function and pass it to the handleSubmit function

Within my component called "MyEditDataForm," I have a redux-form where I pass a submit handling function like this: const myHandleSubmit = ({ firstInputFieldName, secondInputFieldName }) => { console.log(firstInputFieldName); console.log(secondInput ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...