Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at:

It's important to note that the navigation bar is fixed and therefore has no height.

There are two specific challenges that I am struggling to resolve:

  1. Upon page load, the active state is initially applied to the contact link. However, if you scroll down by just 1px, the active state correctly switches to the home link.
  2. I've been unable to modify the script to focus on anchors within an element with a particular ID. In other words, I only want the script to apply the active state to elements within the <nav> tag.

Any assistance on this matter would be highly appreciated.

@rrfive

For your convenience, here is the annotated script:

$(document).ready(function() {
//Get Sections top position
function getTargetTop(elem){

    //fetch the id of the section header from the navigation's href (e.g., "#html")
    var id = elem.attr("href");

    //Height of the navigation
    var offset = 0;

    //Determine the distance from the top and deduct the nav's height
    return $(id).offset().top - offset;
}

//Smooth scroll when a user clicks a link starting with #
$('a[href^="#"]').click(function(event) {

    //calculate the distance from the top of the section referenced in the href
    var target = getTargetTop($(this));

    //scroll to that section
    $('html, body').animate({scrollTop:target}, 500);

    //prevent the browser from immediately jumping to the section
    event.preventDefault();
});

//Pull sections from the main nav
var sections = $('a[href^="#"]');

// Check each section to see if it's at the top; if so, add an active class
function checkSectionSelected(scrolledTo){
    //Define how close the top must be to the section
    var threshold = 54;

    var i;

    for (i = 0; i < sections.length; i++) {

        //retrieve the next nav item
        var section = $(sections[i]);

        //determine the distance from the top
        var target = getTargetTop(section);

        //Verify if the section is at the top of the page
        if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
            sections.removeClass("active");
            section.addClass("active");
        }
    };
}

//Check if the page is already scrolled to a section
checkSectionSelected($(window).scrollTop());

$(window).scroll(function(e){
    checkSectionSelected($(window).scrollTop())
});

});

Answer №1

Your current plugin is designed to detect the positioning of

<div class="section"></div>
elements on the webpage. However, when these sections are set to display:none;, they all register as being "0 pixels" from the top of the page. This issue causes the detection process to stop at the last visible section, in this case, the "CONTACT" section.

To resolve this problem, you can simply remove the display:none; attribute from the .section selector in your CSS file. Once this change is implemented, the plugin should function correctly.

.section {
    /*display: none; <-- You can keep this line commented out.*/
    height: 100%;
    min-width: 990px;
}

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

I am trying to figure out how to properly utilize server-only functions within Next.js middleware

In my current project, I am utilizing Next.js 13 along with the App Router feature. While attempting to include a server-specific fetch function in middleware.js, an error message is encountered: Error: Unable to import this module from a Client Compone ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Sorting nested table rows in vueJS is an essential feature to enhance

I am working with a json object list (carriers) that looks like this: https://i.stack.imgur.com/0FAKw.png Within my *.vue file, I am rendering this using the following code: <tr v-for="carrier in this.carriers"> <td>{{ carrier.id ...

Retrieving ng-model using ng-change in AngularJS

Here is an example of the HTML code I am currently working with: <select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select> This HTML snippet is being populated by the following object containing a ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Display the value in Vue.js as a price format while maintaining it as an integer

I have created a Vue component called "formatted-number" which takes in an integer value (e.g. 1234) and currently displays it as a string (e.g. "12.34") to represent a price in a textfield, with the appropriate "," or "." based on the country. However, I ...

Establishing the NumbroJS cultural settings

I have been attempting to modify numbro's culture. I initially tried the straightforward method, but encountered an error: Unknown culture : ' + code numbro.culture('fr-FR'); My attempt looked like this: const br = require('numb ...

Implementing Asynchronous Rendering in React Router 4

I've been working with React Router 4 and trying to implement Redirect(Auth) following a guide. However, I'm facing an issue with rendering based on the promise returned by an AJAX call. It seems like my rendering logic inside the promise is not ...

Using the symbol for pi in a JavaScript program rather than its numerical value, while still performing calculations with the numerical value behind the scenes

I am working on a calculator project where I want the symbol for pi to be displayed instead of the numerical value. Here is the relevant function: function Pi(pi) { document.getElementById('resultArea').innerHTML += pi; eval(document.ge ...

Change the anchor text dynamically with JQuery

The page contains href links with incomplete text. For example, the link text displayed on the page is "link1", but it should actually be "link1 - Module33". Both the page text and actual text start with the same initial text ("link1" in this case). I retr ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...

Are you encountering difficulties while managing back pressure as anticipated when applying node request or axios in combination with streams for downloading and extracting files?

We have encountered a peculiar problem while trying to download and decompress a large file of approximately 6 GB (which decompresses to around 64 GB) using the HTTP protocol. To achieve this, we are utilizing either Node.js' request library or axios. ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

A step-by-step guide on enhancing error message handling for Reactive forms in Angular

Here is a code snippet that I'm working on: public errorMessages; ngOnInit(): void { this.startErrorMessage(); } private startErrorMessage() { this.errorMessages = maxLength: this.translate.instant(' ...

What could be causing the async request with await to not properly wait for the response data?

I'm having trouble with the await function in my code, can anyone provide assistance? I've followed tutorials and copied the code exactly as shown but it still doesn't work. The CardsID array needs to be filled before I call console.log(Card ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...