Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive.

For example, if I scroll down twice, the value will be 2. Then, if I scroll up once, the value will decrease to 1.

Answer №1

$(document).ready(function(){
    var currentPosition = 0;
    var moveCounter = 0;
    $(window).scroll(function(){
        var currentScrollPos = $(this).scrollTop();
        if (currentScrollPos > currentPosition) {
            moveCounter -= 1;
        } else {
            moveCounter += 1;
        }
        currentPosition = currentScrollPos;
    });
});

This script tracks the movement of a scrollbar. The variable currentPosition keeps track of how many pixels the scrollbar has been moved downwards, starting at zero initially as the scrollbar is at the top position.

When scrolling occurs, currentScrollPos records the current position of the scrollbar and then compares this value with the previous one:

If the current position is greater than the saved position, it means the scrollbar has scrolled downwards, so the moveCounter is incremented by 1. Conversely, if currentScrollPos is less than currentPosition, the moveCounter is decremented by 1.

To ensure the functionality of the code, we update the current position to be compared with for subsequent scroll events.

Answer №2

Check out this potential solution to address your query

let scrollingCount = 0, 
    latestScrollPos = 0,
    docRoot = document.documentElement,
    topScroll = 0;

// Adding event listener for window scroll
$(window).bind('scroll', function (e) {
    topScroll = (window.pageYOffset || docRoot.scrollTop) - (docRoot.clientTop || 0);

    if (latestScrollPos < topScroll) {
        // Scrolling down, incrementing count
        scrollingCount += 1;
    } else {
        // Scrolling up, decrementing count
        scrollingCount -= 1;
    }

    // Storing the latest scroll position for future calculations
    latestScrollPos = topScroll;
});

Answer №3

scrolling=0;
$(document).ready(function(){
  $("div").scroll(function(){
    $("span").text(scrolling+=1);
  });
});

Answer №4

$(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.backToTop').fadeIn();
        } else {
            $('.backToTop').fadeOut();
        }
    });

//Transition to top when clicked
$('.backToTop').click(function () {
    $('html, body').animate({ scrollTop: 0 }, 800);
    return false;
});

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

Navigating through ASP.NET MVC using jqGrid

I'm attempting to generate a link to a URL like home/details/1 within a jqGrid column. The provided documentation states: showlink {baseLinkUrl: '', showAction: 'show', addParam:'&key=2'} Please note that the addPara ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

How to keep child elements in BeautifulSoup using Python?

I need help with the following markup: <p>Sample text. Click <a href="google.com">Here</a></p> Can someone assist me in replacing the <p> tag with <span> while keeping the children and text of the tag unchanged? ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

Guide to aligning a URL in an HTML file

Greetings all, I'm new to HTML and struggling with how to center a URL on my webpage. For example: <a href="http://www.google.com"> Click Here to Open Google </a> I attempted using the tag and the STYLE attribute but without success. ...

"Displaying the state value retrieved from a custom hook is not working as expected

Creating a custom hook, Custom.js: import React, {useState, useEffect} from 'react'; import Clarifai from 'clarifai'; const app = new Clarifai.App({ apiKey: 'XXXXXXXXXXXXXX' }) const CustomHook = () => { const [i ...

I'm having trouble displaying the Facebook page plugin on my HTML website

I encountered a minor issue. I attempted to add the "Facebook page plugin" on a test website. I copied the code from the official Facebook plugin page: <!-- 1. Include the JavaScript SDK on your page once, ideally right after the opening <body> t ...

Stop users from being able to select or highlight text within a content editable div

Is there a method to develop a content-editable div where users are unable to select or highlight content, but can still input information? I'm interested in creating an interface that forces users to delete and enter data character by character, with ...

Saving components locally (vue2)

Looking for help with passing data from Props to Data in vue.js? Check out this Stack Overflow discussion. If you're running into issues, take a look at this sandbox example: https://codesandbox.io/s/u3mr8. Concerned about side effects of copying ob ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

What is the method for accessing the value of variable "a" in the following code?

request(target, function (err, resp, body) { $ = cheerio.load(body); links = $('a'); $(links).each(function (i, link) { if ($(link).text().match('worker')) { var a = $(link).attr('href').toStri ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Leveraging information beyond the socket.on function

I'm trying to work with socket data in a way that allows me to compare it outside of the initial socket.on function. I've attempted using global variables without success. One thought I had was grouping the data, but one is an io.emit and the oth ...

To access a restricted selection of images stored in Firebase

Is there a way to load additional images from Firebase by clicking a button? I created a function that looks like this: onLoadMore() { if (this.all.length > 1 ) { const lastLoadedPost = _.last(this.all); const lastLoadedPostKey = lastLoadedP ...

Adding a new column for each array element within a jQuery foreach loop is a simple task that

I have a request where I am receiving three arrays in JSON format and I want to showcase each array in its own column. How can I accomplish this task? Below is the $.post function: $.post("/booking/times", { id: $("#user_id").val(), ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

Retrieve form input from a servlet using a name attribute such as "input[]"

Looking to retrieve input values from a form on my JSP page where each input shares the same name. Take a look at this JSFiddle Any suggestions on how I can access these inputs from my servlet? I attempted using String[] description = request.getParamete ...

Locate the closest text to an element within an HTML document

My HTML content contains specific tags with text and images. If I am able to select an image, is there a way to retrieve the text nearest to that image? <div class="topStory"> <div class="photo"> <a href="somelink"><img src="s ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...