My code gets disrupted when I switch between ids and classes

I'm currently learning about javascript and jquery, attempting to implement various scripts. I successfully executed the following script:

jQuery(document).ready(function($) {
  var scroll_start = 0;
  var startchange = $('#homepage-header');
  var offset = startchange.offset();
  if (startchange.length) {
    $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if (scroll_start >= offset.top) {
        $("#nav-toggle em").css('background-color', '#ffffff');
      }
    });
  }
});
jQuery(document).ready(function($) {
  var scroll_start = 0;
  var startchange = $('#cosafacciamo');
  var offset = startchange.offset();
  if (startchange.length) {
    $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if (scroll_start >= offset.top) {
        $("#nav-toggle em").css('background-color', '#000000');
      }
    });
  }
});

...and so on for other sections...

Later on, I attempted to simplify the above script into this:

jQuery(document).ready(function($) {
  var scroll_start = 0;
  var startchange = $('.white');
  var offset = startchange.offset();
  if (startchange.length) {
    $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if (scroll_start > offset.top) {
        $("#nav-toggle em").css('background-color', '#ffffff');
      }
    });
  }
});
jQuery(document).ready(function($) {
  var scroll_start = 0;
  var startchange = $('.dark');
  var offset = startchange.offset();
  if (startchange.length) {
    $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if (scroll_start > offset.top) {
        $("#nav-toggle em").css('background-color', '#000000');
      }
    });
  }
});

Although I replaced IDs with classes in the second script, it only works for the first two sections (#homepage-header and #cosafacciamo) and does not change the nav-toggle color anymore.

Why is the first script functioning correctly while the second one isn't? What mistake am I making?

Your assistance would be greatly appreciated! Thank you :)

Answer №1

Upon setting var startchange = $('.white'), the jQuery object $('.white') contains multiple DOM elements, but only the numbers for the first one are returned by the .offset() method.

To address this issue, utilize .each() to iterate through each DOM element individually.

An alternative approach is to employ JavaScript functions to maintain code consistency. You can try the following (not tested):

function doMyThing(startchange,color) {
  var scroll_start = 0;
  if (startchange.length) {
    startchange.each(function() {
      var offset = $(this).offset();
      $(document).scroll(function() {
        scroll_start = $(this).scrollTop();
        if (scroll_start >= offset.top) {
          $("#nav-toggle em").css('background-color', color);
        }
      }); // scroll
    } // if
  } // doMyThing
});

jQuery(document).ready(function($) {
  doMyThing($('.white'),'#ffffff'); 
  doMyThing($('.black'),'#000000'); 
});

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

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

Mapping out your data effectively requires following the correct steps to ensure accuracy and clarity

My goal is to display a map using Mapbox only once the data is ready. The Vuex store code I am working with is as follows: /store/index.js import Vue from "vue"; import Vuex from "vuex"; import _ from "lodash"; import { bac ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

Clicking the ASP button does not trigger the onclick event when a web user control is included on the webpage

I have been working on a web form application that I developed using the visual studio template. The template includes a content placeholder that gets replaced by the content of each accessed page. One particular page, which contains server controls like t ...

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

Using Node.js and Multer to update a file uploaded to MongoDB

I have a website that allows users to upload files, but I also want them to be able to edit those files. This would involve the user pressing "edit" and replacing the existing file in the database with a new one. Normally, you can use findByIdAndUpdate for ...

In JavaScript, the clearTimeout function may not always return a

Could someone please help me troubleshoot the issue in my code snippet below? I am trying to declare a public variable and assign it to a setTimeout function. If the variable is not null, I want to clear the timeout before setting it again. However, when ...

Unanticipated Behavior in JavaScript (jQuery): Triggering a Function Instead of Submitting a Form

I'm confused about something. Here's my issue: I have a specific type of form declaration where jQuery processes the form data and sends an Ajax request. Inside the form, there are buttons - one for form submission (Ajax) and another for calling ...

Guide to launching a web browser within a Phonegap app with a button click event

We are developing a PhoneGap application using HTML and JavaScript. Our goal is to integrate PayPal's website so that users can make payments with a simple button click event within the app, and then seamlessly return back to the application afterward ...

Utilize the DataTables plugin to arrange a column based on icons with hidden boolean values in rows

I am currently utilizing the DataTables plugin to enhance my HTML table. While I have managed to successfully implement most functionalities, I am facing a challenge with the boolean column. This particular column consists of icons representing X (value 0) ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

Tips for decreasing the width of a Grid column in MUI React

I have a total of 8 columns. The first column should be the smallest to accommodate a checkbox and does not require much space. I attempted to adjust the xl, lg, md values to 0.5 but was unsuccessful. Is there an alternative method to change the width of t ...

Transitioning from a see-through navigation bar to a vibrant colored menu as

I consider myself a novice when it comes to JavaScript. My goal is to create a Transparent Menu that smoothly transitions from transparent to white with a box shadow as I scroll down the page. However, the JavaScript code I have implemented does not seem ...

Learn the position of a div element that appears following the lazy loading of images

I am struggling to make a div sticky below a set of lazy load images. The issue lies in the fact that the offset of the div keeps changing due to the lazy loading images pushing it down. There are 4 images with unknown heights, making it difficult to acc ...

Ways to retrieve dictionary keys as an array in Angular

Here is an example of an Angular dictionary: { ARRAY1: [{...}, {...}, {...}] ARRAY2: [{...}, {...}, {...}] ARRAY3: [{...}, {...}] ARRAY4: [{...}] } I want to show all the keys of arrays from this dictionary on an HTML page. I attempted to do ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

The ASP.NET Core framework features a static top menu bar and a fixed left-hand side menu for seamless navigation

I am currently utilizing ASP.NET Core 6, jQuery, and Bootstrap in my project. I have a specific screen layout where I want the left-hand side menu and the top menu to remain fixed in their positions, while only the input details section should be able to s ...

Custom HTML on Joomla causing carousel to vanish

I've encountered an issue with my Joomla website where my carousel images are disappearing. I have a code snippet from W3 Schools for an automatic banner that works perfectly fine when opened in a browser using Notepad++, but when inserted into a cust ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

JavaScript loop through an array of objects

Is there a way to loop through and retrieve all of the addresses? const name = { john: [ { age: 21, address: 'LA', } ], sam: [ { age: 26, address: 'California' } ] } I have tried using th ...