Apply a class to an element as it comes into view 100 pixels before scrolling past it

I need help adding a specific class to an element (class abc) when it is 100px below the top of the viewport. Currently, the class is being added to all divs instead of individual elements. Any advice on how to fix this?

$(function() {
  $(document).scroll(function() {
    if ($(this).scrollTop() >= $('.abc').offset().top - 100) {
      $(".abc").addClass("color");
    } else {
      $(".abc").removeClass("color");
    }
  });
});
#header {
  height: 150px;
}

.abc {
  background-color: orange;
}

.color {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
  <h1>Header</h1>
</div>
<div class="abc">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper aliquam neque, id condimentum orci egestas ac. Maecenas ullamcorper semper finibus. Quisque vitae semper lorem, ut mattis mi. Maecenas ut porta enim. Duis tellus sem, tincidunt
  vitae turpis tristique, laoreet sodales nunc. Donec laoreet sollicitudin nibh, a porta risus elementum id. Vivamus et quam nec enim tincidunt tempus in sed ipsum. Quisque non arcu sem. Nulla eget massa ultricies, dignissim erat vel, tristique turpis.
  Pellentesque non maximus est, in feugiat nibh. Morbi enim elit, sodales ac leo eget, interdum imperdiet elit. Nunc dapibus scelerisque aliquet.
</div>
<div class="abc">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper aliquam neque, id condimentum orci egestas ac. Maecenas ullamcorper semper finibus. Quisque vitae semper lorem, ut mattis mi. Maecenas ut porta enim. Duis tellus sem, tincidunt
  vitae turpis tristique, laoreet sodales nunc. Donec laoreet sollicitudin nibh, a porta risus elementum id. Vivamus et quam nec enim tincidunt tempus in sed ipsum. Quisque non arcu sem. Nulla eget massa ultricies, dignissim erat vel, tristique turpis.
  Pellentesque non maximus est, in feugiat nibh. Morbi enim elit, sodales ac leo eget, interdum imperdiet elit. Nunc dapibus scelerisque aliquet.
</div>
<div class="abc">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper aliquam neque, id condimentum orci egestas ac. Maecenas ullamcorper semper finibus. Quisque vitae semper lorem, ut mattis mi. Maecenas ut porta enim. Duis tellus sem, tincidunt
  vitae turpis tristique, laoreet sodales nunc. Donec laoreet sollicitudin nibh, a porta risus elementum id. Vivamus et quam nec enim tincidunt tempus in sed ipsum. Quisque non arcu sem. Nulla eget massa ultricies, dignissim erat vel, tristique turpis.
  Pellentesque non maximus est, in feugiat nibh. Morbi enim elit, sodales ac leo eget, interdum imperdiet elit. Nunc dapibus scelerisque aliquet.
</div>
<div class="abc">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper aliquam neque, id condimentum orci egestas ac. Maecenas ullamcorper semper finibus. Quisque vitae semper lorem, ut mattis mi. Maecenas ut porta enim. Duis tellus sem, tincidunt
  vitae turpis tristique, laoreet sodales nunc. Donec laoreet sollicitudin nibh, a porta risus elementum id. Vivamus et quam nec enim tincidunt tempus in sed ipsum. Quisque non arcu sem. Nulla eget massa ultricies, dignissim erat vel, tristique turpis.
  Pellentesque non maximus est, in feugiat nibh. Morbi enim elit, sodales ac leo eget, interdum imperdiet elit. Nunc dapibus scelerisque aliquet.
</div>
<div class="abc">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper aliquam neque, id condimentum orci egestas ac. Maecenas ullamcorper semper finibus. Quisque vitae semper lorem, ut mattis mi. Maecenas ut porta enim. Duis tellus sem, tincidunt
  vitae turpis tristique, laoreet sodales nunc. Donec laoreet sollicitudin nibh, a porta risus elementum id. Vivamus et quam nec enim tincidunt tempus in sed ipsum. Quisque non arcu sem. Nulla eget massa ultricies, dignissim erat vel, tristique turpis.
  Pellentesque non maximus est, in feugiat nibh. Morbi enim elit, sodales ac leo eget, interdum imperdiet elit. Nunc dapibus scelerisque aliquet.
</div>

Answer №1

Your approach is correct when checking a single element, but in order to apply this to a collection, you'll need to iterate through each element and evaluate its position individually. Here's an example of how you can achieve that:

$(function() {
  $(document).scroll(function() {
    var scrollTop = $(this).scrollTop();
    
    $('.abc').each(function() {
      $(this).toggleClass('color', scrollTop >= $(this).offset().top - 100);
    });
  });
});
#header { height: 150px; }
.abc { background-color: orange; }
.color { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
  <h1>Header</h1>
</div>

<!-- Several div elements with the class "abc" and Lorem Ipsum text -->

Answer №2

Perhaps we can attempt something along these lines.

 $('.abc').each(function(){ //Iterate through each .abc element
   if($(window).scrollTop() >= $(this).offset().top - 100) { //Check if it is within the offset range
      $('.abc').removeClass("color"); //Remove all color classes
      $(this).addClass("color"); //Add color class to the current .abc element
   } 
 })

Please let me know if this solution works. You can view an example here.
Best regards!

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

Issues with HTML5 video playback have been reported in both Chrome and Firefox browsers

I'm having trouble getting the following HTML5 Video code to work. Can someone help me spot what I might be missing? <video width="267" poster="Poster.gif" height="209"> <source src="6Minutes_1.mp4" type="video/mp4"></source> <so ...

Having difficulty manually concealing the launch image on the physical device

When testing my trigger.io app on the Android simulator or my Nexus phone, I can manually hide the launch image through code successfully. However, when running the app on the iOS simulator, the launch image remains visible. Additionally, when debugging di ...

Ways to delay the execution of a loop using setTimeout or setInterval

In my code, I have an array named RotatorNames which includes different elements. Let's say it currently includes ["rotatorA","rotatorB","rotatorC"]. My goal is to loop through this array and trigger a click event for each item. While I have made pro ...

Error message encountered when attempting to process json-encoded JavaScript using Ajax

I am struggling with an HTML document that includes: <li id="li_273" data-pricefield="special" data-pricevalue="0" > <label class="description" for="element_273">Helium Foil Balloon #1 </label> <div> ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

Setting up a specific print media query for the body element through JavaScript

I'm facing an issue with my web page that has a bootstrap modal which pops up when a button is clicked. I've added a print media query to print the content of the modal, but it's causing a problem. When I include the media query in the CSS, ...

Troubleshooting the malfunctioning Bootstrap Dropdown Navbar in Rails 6

I am currently integrating Bootstrap with a Rails 6 application. I utilized yarn to install jquery and popper.js. Despite including a dropdown in my navbar, it fails to open and instead just redirects me to the current link with an added #, which serves no ...

Update the color of a span in JQuery when its value equals 0

Currently, my goal is to update the color of a span tag only if its value is 0. I attempted to achieve this with the following code: $('span.number:contains("0")').css('color', '#C1C1C1'); However, this code also changes the ...

Tips for hovering over a link with Webdriver

Currently, for my project, I am utilizing Selenium Webdriver. Successfully automating the functionality to mouse over an image has been achieved. However, there seems to be an issue when attempting to trigger a mouse-over event on a hyperlink using the sam ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Utilizing Pusher to transfer user deposit and withdrawal information from client to Node.js (Express) server: A step-by-step guide

I have subscribed to "my-channel" and connected to "my-event" on the client side. pusher.html <!DOCTYPE html> <head> <title>Pusher Test</title> <script src="https://js.pusher.com/5.0/pusher.min.js"></script> < ...

Encountering a glitch while attempting to execute my test on webdriverio

Lately, I've encountered an issue while attempting to execute my webdriverio tests following an upgrade of my node version. The error message that now pops up is: 2022-01-11T12:45:05.628Z DEBUG @wdio/config:utils: Couldn't find ts-node package, n ...

Utilizing jQuery and ajax to send emails within WordPress

Currently facing a minor issue while working on a straightforward quotation form in WordPress. I have two forms; the first one sends data to jQuery for calculations (using minimal options, hence no need for a database), then displays an HTML row. Everythin ...

Reloading specific content on an ASP.NET CORE Razor Pages website

Hello, I am new to Razor pages and recently integrated the AdminLTE template into my Razor Page application successfully. In the _Layout.chtml file, I inserted the sidebar menu with anchor tags that link to specific pages, as well as the header bar and fo ...

Selecting Jquery Mobile Option from JSON Data

I am working on displaying JSON data in an HTML fieldset with radio choices. However, when I try to show the HTML code, it displays "undefined" instead. Here is the code snippet I am using: var str_html; var str_html; str_title = item.title || null; str ...

Adaptive scrolling backdrop

As a complete novice in HTML/CSS, I am attempting to create my portfolio. My approach is to start with the most basic elements, beginning with the background. Since my main page is a large scrollable one, I want the background to fit the screen size of the ...

Creating a vertical loop animation for a cube in Three.js

I'm trying to make this box move in both the up and down directions, but currently it only moves up. BoxGeo = new HREE.BoxGeometry(10,10,10) BoxMat = new THREE.MeshPhongMaterial({ color: 0xf3e54f }), cab = new THREE.Mesh ( BoxGe ...

I'm having trouble displaying the partial view called by my action in ajax.beginform. Why isn't it showing up on the page

I am encountering an issue with a page that includes a viewmodel. When a button is clicked, it triggers an ajax form submission: @using (Ajax.BeginForm("finalstatus", "User", null, new AjaxOptions { HttpMethod = "POST", ...

The success function of the ajax request is not initiating until I halt the page

I am currently working on a server using the Django 1.4 development environment on Open-SUSE. The Issue I'm Facing Although my jquery ajax request is triggered, the success function does not execute until I manually stop the page in my browser. Att ...