Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no errors showing up, I am struggling to debug this issue.

$(window).load(function() {
    var $header = $("header");
    var numberOfSections = $("section").length;   
    var sectionOffsets = [];
    var sectionColour = $("section").eq(i).data("colour");

    for(var i = 0; i < numberOfSections; i++) {
        sectionOffsets.push($("section").eq(i).offset().top);
    }            

    $(window).scroll(function() {
        var scrollTop = $(this).scrollTop();            

        for(var i = 0; i < numberOfSections; i++) {
            if(scrollTop > sectionOffsets[i] - 180) {
                $header.css('color', 'sectionColour');
            }
        }
    });
});

Answer №1

It seems like an oversight, but the line of code

var sectionColour = $("section").eq(i).data("colour");

is in the wrong place. It relies on a variable i that is only defined within the window scroll handler.

Remember to fetch the section color each time the scroll handler is activated, not just on window load. Move the mentioned line into the loop inside the scroll handler.

Furthermore, as indicated in the comments, make sure to treat sectionColour as a variable, not a string as it currently appears. Remove the single quote marks so that 'sectionColour' becomes sectionColour.

Here's the corrected version of your code:

$(window).load(function() {
    var $header = $("header");
    var numberOfSections = $("section").length;   
    var sectionOffsets = [];

    for(var i = 0; i < numberOfSections; i++) {
        sectionOffsets.push($("section").eq(i).offset().top);
    }            

    $(window).scroll(function() {
        var scrollTop = $(this).scrollTop();            

        for(var i = 0; i < numberOfSections; i++) {
            if(scrollTop > sectionOffsets[i] - 180) {
                var sectionColour = $("section").eq(i).data("colour");
                $header.css('color', sectionColour);
            }
        }
    });
});

As a side note, you can simplify your code like this:

$(window).scroll(function () {
     $("section").each(function () {
        if ($(window).scrollTop() > $(this).offset().top - 180) {
            $("header").css('color', $(this).data("colour"));
        }
    });
}).scroll();

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

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

Acquiring HTML form information in ASP.NET controller

Currently, I have a view that includes an HTML login form and I am working on passing the form values to a controller via post. My goal is to display the user's username using the Content method once the form is submitted. However, I am facing an issu ...

Understanding how to bind data in JavaScript client-side templates

I've started incorporating Client Side templates into my JavaScript code. Currently, I'm using the $create method to bind a Sys.UI.DataView to my data. The "data" variable contains a JSON result with 100 records, all of which are being bound by ...

Decoding date formats using d3.js version 4

Currently diving into the world of coding with d3.js by working on my very first d3 mini project, following the Free Code Camp curriculum. The goal is to create a basic bar graph using this json file. However, I've hit a roadblock while trying to form ...

Obtaining localStream for muting microphone during SIP.js call reception

My approach to muting the microphone involves using a mediastream obtained through the sessionDescriptionHandler's userMedia event. session.sessionDescriptionHandler.on('userMedia', onUserMediaObtained.bind(this)) function onUserMediaObta ...

What is the best approach to incorporating two distinct grid layouts within a single section?

I am attempting to replicate the header-graphic navigation found on this website: It appears that they are not using a grid for the header-graphic area, but rather keeping them separated as 2 divs within their Hero block container. I am interested in recr ...

Issue with hashtag in regular expressions

Looking for a way to identify and link hashtag words with an anchor tag? Here's a snippet showcasing the concept: <p class="display"></p> var content = "I enjoy #blueSky. My favorite color is #green. #sky is amazing"; ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error: Ex ...

Leveraging the GetListItems method via an Ajax request in SharePoint 2010

I'm currently working on implementing an ajax call to fetch list items from SharePoint by utilizing the Lists.asmx service. Despite following the correct formatting, I keep encountering a persistent 302 error. Is there something crucial that I may be ...

Code: Ensuring URL spaces are maintained

In my Angular 4 project, I have a service with a delete API that requires two strings as parameters. Here is an example of how it looks: this.http.delete(this.url + 'api/v1/ReportingService/collectionID/'+ '45902' +'/'+' ...

How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters. Below is the Home.vue page: <template>   <div class="home">     <h1>       All Destinations     </h1>     < ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

"div p" or "div * p"? Do they have the same meaning or is there a difference between them?

My knowledge of the "grandchild" selector in CSS was limited until I came across this insightful article. Intrigued, I decided to experiment with it and found that it resembles the universal selector (which targets all elements). Let's take a look at ...

What is the best way to declare a global TypeScript variable in a definition file to make it accessible for import?

My issue revolves around an external JS library that contains a global parameter: function Thing() { ... } ... var thing = new Thing(); I have a TypeScript definition file named thing.d.ts with the following content: declare var thing: ThingStatic; ex ...

Thymeleaf is responsible for fetching the static resources by referencing the REST URI

I am currently utilizing thymeleaf as my chosen template engine for a spring boot project. Here is the directory structure: src/main/ |- java | - UserAdministrationController.java |- resources | - static | - admin | - css ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

having trouble with npm installation of firebase-tools

I am encountering an issue while attempting to set up firebase-tools for my android studio project. Here is the error message that I am facing: Microsoft Windows [Version 10.0.15063] (c) 2017 Microsoft Corporation. All rights reserved. C:\WINDOWS&bs ...

Verify whether the content within the Div has been modified

I am currently making changes to content within a <div> element. I would like to determine if the data in the <div> has been modified and, if so, save it in a session to persist on refresh. How can I verify if the data has been edited and then ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...