Measuring the pixel distance of scrolling on a page with overflow hidden

I am trying to implement a functionality where a class is toggled for the body element on a page with hidden overflow and single screen, based on the amount of scroll. However, there is a challenge: the scrolling behavior involves animation rather than actual scrolling from top.

First, I attempted the following code:

if ($(window).scrollTop() > 1000){
    $('body').addClass( "endScroll");
}
else {
    $('body').removeClass("endScroll");
}

Unfortunately, this method did not work as expected due to the nature of the single screen with hidden overflow.

Subsequently, I tried a different approach:

$(document).bind('mousewheel', function(e) {
    var delta = e.originalEvent.wheelDelta;

    if (delta < 0) {
        $('body').addClass("endScroll");
    } else if (delta > 0) {
        $('body').removeClass("endScroll");
    }

});

Although this solution successfully adds the class, it does so immediately upon any scrolling action. I am struggling to find a way to toggle the class only after scrolling more than 1000 pixels.

Your help would be greatly appreciated!

Answer №1

UPDATE: Here is a revised solution that aligns more closely with your requirements. To track how much the user has scrolled, you can utilize a tracking variable:

var scrollPosition = 0;
$(document).bind('mousewheel', function(event) {
    scrollPosition += event.originalEvent.wheelDelta;        
    if (scrollPosition > 0) scrollPosition = 0;     

    console.log(scrollPosition);        

    if (scrollPosition < -1000) {
        $('body').addClass( "endScroll");
    } else {
        $('body').removeClass("endScroll");
    }    
});

UPDATE 2: Ensuring compatibility with Firefox:

var scrollPosition = 0;
var mouseWheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
$(document).bind(mouseWheelEvent, function(e) {
    var offset = -1 * e.originalEvent.wheelDelta;

    if (mouseWheelEvent == "DOMMouseScroll"){
      offset = e.originalEvent.layerY - e.originalEvent.clientY;
    }

    scrollPosition += offset;        
    if (scrollPosition < 0) scrollPosition = 0;
    console.log(scrollPosition);

    if (scrollPosition > 1000) {
        $('body').addClass( "endScroll");
    } else {
        $('body').removeClass("endScroll");
    }    
});

Answer №2

Experience the magic of scrolling to 1000px and watch as the background transforms from black to red when you scroll up.

$(window).on("scroll", function() {
    if($(window).scrollTop() >  1000){
        $(".scroll-div").addClass('scroll-div-red');
    }
    else{
    $(".scroll-div").removeClass('scroll-div-red');   
    }
});
.scroll-div{
  background:#000;
  height:1500px;
  overflow:hidden;
}
.scroll-div-red.scroll-div{
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll-div">

</div>

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

Brother or sister is never empty, as every comment is considered an entity

When going through a list of jQuery objects, I want to verify if the nextSibling attribute is null. However, I found that an HTML comment also counts as a sibling object. How can I address this issue? I am looking for an if statement that will trigger fo ...

Creating a chat interface with chat bubbles in React JS can be done by implementing components such as Message

Having some JSON data stored in dummyData, I am seeking guidance on how to position chat bubbles on the left and right based on the direction. My framework of choice is Material UI along with the context API. The attached image serves as a visual reference ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Using Laravel with Ajax can sometimes result in successful requests, while other times they may fail

I am facing some issues with my code as a junior programmer. Sometimes when I call data using Ajax in laravel 5.7, it is successful and the data is retrieved. However, upon refreshing, sometimes it is incomplete and logs show an error 500 in my PHP. Strang ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...

When deciding between utilizing a Javascript animation library and generating dynamically injected <style> tags in the header, consider the pros and cons of each

We are currently in the process of developing a sophisticated single-page application that allows users to create animations on various widgets. For example, a widget button can be animated from left to right with changes in opacity over a set duration. Ad ...

Can one function be invoked from another function in Node.js?

As I delve into learning Node.js through the process of converting an existing Rails project, I find myself grappling with callbacks and the asynchronous nature of Node. It has been a challenging journey to wrap my head around these concepts. Initially, m ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Create a React Native layout with a set width and the ability to stretch to fill

Is there a way to achieve this layout in react-native? I am looking to have a component with a fixed width on the right side, while another component on the left side takes up the remaining space. https://i.sstatic.net/3c6q6.png ...

Is it possible to develop in React without using webpack, relying solely on Gulp instead?

Although I appreciate some aspects of Webpack, my enthusiasm for it wanes as the configuration files grow beyond 15 lines. It becomes overly cryptic, difficult to configure, and time-consuming. Therefore, I tend to reserve its use for just a couple of task ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue! I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should app ...

Utilizing Python Selenium to Interact with Buttons

Encountering an issue while trying to use Selenium to click on a tab or button within my web application. Below are the code snippet and CSS selectors: Error message: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: #t ...

Print the page number using HTML and PHP

Is there a way to center page numbers in HTML? I have the code below that echoes the numbers, but they always appear on the left side of the page. I tried wrapping them in a div to center them, which worked, but then each number is enclosed in its own d ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

How can I insert a button into a Flatlist using React Native?

Is there a way to add a single scrollable button inside a FlatList without duplicating it? I've been experiencing issues where adding a button inside the FlatList results in multiple buttons being displayed. On the other hand, placing the button outs ...

Adaptable Design for Smartphones

Currently in the process of creating a website for my brother with Joomla 3.4 and Bootstrap. This marks my first venture into building a responsive site, so I'm seeking guidance on essential elements to include in my CSS such as font sizes in specific ...

Incorporating a View into a Sidebar in CakePHP

I'm currently facing some challenges understanding the concepts of CakePHP's views, blocks, and layouts. My goal is to have a left and right sidebar displayed on every page, with content that may vary. Right now, I have the right sidebar set up ...

How to include a listview in the footer navbar using jQuery Mobile

Is there a way to include areas instead of links in the footer navbar, and then incorporate a list view within one of those areas? The navbar only seems to accept anchors, not divs, and the styling of the list view is not displaying correctly in the provid ...