utilizing jquery to trigger events based on scrolling

I am working with a HTML class that contains various elements. I want to add a new class to the first element when it reaches the top of those elements, and then continue adding the class to the subsequent elements as the page is scrolled. I've attempted the following code:

var element = $(".element"); 
$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    for(var i = 0; i < element.length ; i++){
        if(scroll > element.eq(i)){
            element.eq(i).addClass("newClass");
        }
})

Here's the HTML snippet:

<div>
    <div class="element">
        <img src="img/image1" />
    </div>
    <div class="element">
        <img src="img/image2" />
    </div>
    <div class="element">
        <img src="img/image3" />
    </div>
</div>

However, the line

element.eq(i).addClass("newClass")
doesn't seem to be functioning properly. Any suggestions on how I should approach this?

Answer №1

attempt to utilize

if(when scrolling > element.eq(i).offset().top - ($(window).height() / 2) ){
    apply a new class to element.eq(i);
 }

VIEW DEMO

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

Step-by-step guide on setting up a unique page within the WordPress admin interface without any pre-loaded default content

I am currently loading my custom WordPress plugin page using the admin_init hook like this: add_action('admin_init','myfunction') function myfunction(){ include("login.php"); return exit; } I check the session value, include t ...

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

What is the best method to delete a value from localStorage using redux-persist?

In my index.js file, I have set up a persist configuration as shown below: import {configureStore, combineReducers} from "@reduxjs/toolkit" import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redu ...

Different ways to conditionally set the expanded prop for the Material UI TreeView component

I am currently working on implementing a tree select feature similar to the one found in antd's tree-select using material ui components. Specifically, I have a TextField and TreeView components from Material-UI stacked vertically. Initially, I want t ...

Tips for dynamically changing the object based on the value type in JavaScript

How can I transform a nested object into a new object using JavaScript? I have an object obj where if the details property is an array, I want to use the first value of the array as the value in JavaScript. function transformObject(obj) { let map = {}; ...

Updating the positions of Mesh objects in Three.js asynchronously

I'm currently working on a Three.js application where I am creating a grid to display various objects. These objects are rendered on the grid based on their positions, which are obtained from data fetched from a REST API that I poll every 300 millisec ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Having trouble with Jest and React IntersectionObserver mock not functioning properly?

While working on my component.test.js file, I attempted to mock the IntersectionObserver using the following code: const mock = ()=>({ observe: jest.fn(), disconnect: jest.fn() }); window.IntersectionObserver = jest.fn().mockImplementation(mock) ...

Challenge with URL paths in ReactJS

My webserver is up and running with all the http endpoints linked to the base URL: http://<some_name>/widget/ On the frontend, I have a ReactJS app. The issue arises after building the ReactJS app, as the built index.html references the following U ...

Retrieving a JavaScript variable from a Python Selenium request

Currently, I am utilizing Python in conjunction with Selenium to monitor changes on our pbx system. A specific value that I require is being retrieved through a JavaScript call and unfortunately, it is not directly written into the HTML code. This has made ...

Edge and Internet Explorer fail to recognize the :focus CSS selector

I am utilizing CSS to make our placeholders jump up when clicked inside, but Edge is not recognizing the CSS. It works fine on every other browser except for Edge. I've tried various solutions but none seem to work on Edge. Any thoughts on what might ...

The Runtime Error encountered in NEXTJS: TypeError - Unable to iterate over 'games' as it is not

Attempting to create my inaugural website that showcases data from an API sans a tutorial. Does it seem like I may have overlooked something? I've successfully fetched the API and confirmed in the console log that the necessary data is present. Howev ...

Utilizing reusable functionalities within Vuex

Currently, while working on my NUXT project, I am facing a situation where I find myself repeatedly copying the same actions into multiple store modules. To streamline this process, I have extracted these actions into a separate file and now import them in ...

Building a HTML table using PHP

My goal is to generate a dynamic table using data from mysql. I am trying to create the table layout as shown in 'demo1', but I am facing challenges with the formatting, similar to what is depicted in 'demo'. The query and values are co ...

What methods are available to load sections of a complex SVG shape asynchronously?

I'm currently in the process of creating a website with a geographic map built using SVG, pulling data from OpenStreetMap. Due to its large size and potential for transformations such as zooming and moving, only a portion of it will be visible on the ...

An error occurred when making an Ajax call through WebClient.DownloadString(url) in the Controller, resulting in an HTTP

Within a JavaScript function, I am making a typical ajax call: $.ajax({ type: 'GET', url: '@Url.Content("~/Incident/LookUpStudent")', data: { userInput: userInputStudentLDN }, success: function (resu ...

The jQuery timer I implemented is not showing up properly on my webpage

Here's a look at my HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/boot ...

Tips for updating and using a map value array as state in React

One React state I am working with is as follows: const [tasksMap, setTasksMap] = useState(new Map()); This map is created using the following code: tasks.forEach((task) => { const key = `${week.year}-${week.weekNo}`; if (!tasksMap.has(key)) { ...

What steps can be taken to resolve webpage loading issues following data insertion into a database using express and node?

My express app has a post route handler (/addpost) for adding data to a database. Everything works perfectly, but the window keeps loading. To prevent the browser from waiting for more data, I know I need to send a response. However, all I want is for th ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...