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

Persistent error function arises from Ajax request in Laravel

Greetings everyone. I'm currently working on my Laravel application and trying to verify the attendance for a specific date, subject, grade in my database table. If the data exists, I have implemented an if statement to display the desired results bas ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

Attempting to construct an 'or' query that relies on the combination of two distinct joined tables

Currently, I am facing a challenge with selecting rows from a PostgreSQL database through Sequelize. I need to retrieve data where the ID exists in either joined table 1 or joined table 2. In my attempts using Sequelize, I used 'include' to quer ...

What's the best method for uploading a file to AWS S3: POST or PUT requests?

Could you please provide insights on the advantages and disadvantages of utilizing POST versus PUT requests for uploading a file to Amazon Web Services S3? Although I have come across some relevant discussions on platforms like StackOverflow, such as this ...

Locate the <a> element using the href text

How can I use jQuery to find a specific link and hide it? I need to locate the link by its text content using jQuery. The code snippet below is not achieving the desired result: <a href="example.com/foo-bar">a website link</a> function rep ...

How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table. Here is the script I am using: <script> ex ...

Why is Puppeteer failing to download to the designated folder using "Page.setDownloadBehavior" in Windows?

When trying to download a file using Puppeteer, I found that the code works perfectly on a Mac OS machine but fails on a Windows machine. The code snippet I used is shown below: await page._client.send( 'Page.setDownloadBehavior', { beha ...

Error code 405: The POST method is not compatible with submitting multiple forms using JavaScript code simultaneously

Having multiple forms on a single page that are all submitted using the same JavaScript code presents some challenges. <form class="form" id="cancelchallenge1" method="POST" action="{{action('ChallengeController@cancelChallenge')}}"> <i ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...

Transferring User ID from Google Tag Manager to GA4 Problem

I'm currently working on a new project and adding some dummy data to the dataLayer of Google Tag Manager from the \_app.tsx file. <Script id="gtg" strategy="beforeInteractive"> { window.dataLayer = window.dataLayer || &b ...

Adding up results from Ajax request based on specific criteria

I am performing an Ajax Request that retrieves data from two different databases. For example, I have 2 databases and my ajax request queries those databases to return the following information: [{"question_id":31,"columnheader":"joene_001","ct_yes":"2"," ...

Issue with connecting Drupal 8 theme styling to website pages

Although the theme is functioning properly, the CSS styles are not being applied. Even when inspecting the developer console in Firefox, there seems to be a disconnect with the page. I verified that manually applying the CSS through the developer console i ...

Looking for the temporary folder created by the nodejs filesystem?

After encountering path issues with writing values from a textarea to a file using fs, I turned to stackoverflow and discovered that the path should be a tmp folder. Following this advice, the terminal indicated success with the process. However, now I am ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

The separator falls short of spanning the entire width of the page

For some reason, I can't seem to make the divider extend to the full length of the page. <TableRow> <TableCell className={classes.tableCell} colSpan={6}> <Box display="grid" gridTemplateColumn ...

Angular library modules for node packages

After developing my latest library, I noticed some red underlines: https://i.stack.imgur.com/ffAjI.png In this package, I plan to incorporate other npm packages like ionic and crypto. I attempted to update the package.json within the library: { "name ...

Is there a way to adjust the margin for a child DIV element using CSS?

Currently, I am working on my website located at www.buildinghunter.com. On the homepage, there are four div elements positioned in the bottom left corner of the page. I am attempting to align two specific divs (id=text-9 and id=text-10) with the other tw ...

I'm experiencing some unusual behavior with the Windows media app when using HTML and CSS

I have a Windows Media Player box on my page, but it overlaps every piece of HTML code. How can I get it to move to the back so that I can still use it? Another problem is that everyone who visits my page needs a plugin to load it, even though most people ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

Display the user's chosen background image as the backdrop for my activity

As I've been exploring various corners of the internet, I've come across a potential technique for accessing the user's background from within my activity. I've brainstormed a couple of ideas (even though they might seem silly, just to ...