Storing the value of the current vertical scroll position in a variable using jQuery

I'm currently dealing with a challenge that involves using the value of (window).scrollTop() as a crucial variable in my project. What I aim to accomplish is to retrieve and utilize the specific scroll value at a particular moment within an if statement, then maintain that value globally for future event handling. To achieve this, I need to capture and fix the initial value returned from the scroll function, without any subsequent changes due to further scrolling activities. My approach involves implementing setInterval() to continuously monitor and capture the desired point. Below is a simplified segment of the code I'm working on:

var $windowend;

var $elone = $('.element-one');
var $eltwo = $('.element-two');


setInterval(function(){

    var $left = $elone.css('left');

    if ($left >= 500) {

    // store scroll value here 
    $windowend = $(window).scrollTop();

    }
}, 100);


$(window).scroll(function(){

    $elone.css({
        'left': $(window).scrollTop()
    })

    $eltwo.css({
    // utilize stored value here
        'left': $windowend
    })

});

The scenario unfolds when the position of the first element reaches or surpasses 500px, prompting me to record the current scrollTop value for tracking the window's scrolling progress. It's pivotal for me to retain the initial value for accurate referencing, even if the scroll position fluctuates post-initial recording.

I trust this explanation conveys the essence of my request. Appreciate your assistance!

Answer №1

Update to this:

var $window = "auto";

var $elementOne = $('.element-one');
var $elementTwo = $('.element-two');


setInterval(function(){  

    var $leftPosition = $elementOne.css('left');

    if ($leftPosition >= 500 && $window =="auto") {

        // insert a number here 
        $window = $(window).scrollTop() + "px";

    }
}, 100);


$(window).scroll(function(){

    $elementOne.css({
        'left': $(window).scrollTop()
    })

    $elementTwo.css({
    // use the inserted number here
        'left': $window
    })

})

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

Design concept - Trigger an action upon clicking a checkbox within a table row

I've been working on implementing a selectable table using material design. I want to trigger an action when a checkbox in a table row is clicked, but my attempts with jQuery have not been successful. Here's the structure of my table: <table ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Customize node.js response by overriding or adding another return statement

I have two variables, FirstName and LastName, that I need to include in the response data. It is important to note that the FirstName and LastName are not stored in the Student table. let result = await Student.get(id) let FirstName = "Paul" let LastName ...

Why is it that consolidating all my jQuery plugins into one file is ineffective?

Prior to this, I included the following scripts: <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/json2.js"></script> <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/jquery-msdropdown/js/jquery.dd.js"></script&g ...

The MongoDB .push operation is returning a null value

Take a look at the GitHub repository where I am actively working: https://github.com/Stick-z/first-media-app I'm currently in the process of creating a website and focusing on the backend development. One of my tasks involves setting up a jokes array ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Connect to a node.js server from a different network

Looking to set up a basic live chat using node.js, socket.io, and express. Managed to get it working on my local network, but wondering if there's a way for someone from another internet connection to connect without me needing to pay for server space ...

Ways to update the DOM once a function has been executed in VUE 3 JS

I'm working on implementing a "like" or "add to favorite" feature in VUE 3. However, I'm facing an issue where the UI doesn't update when I like or unlike something. It only refreshes properly. I'm using backend functions for liking and ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

When representing audio as sound bars on a canvas, the previous drawing is retained if canvas height is not specified

After obtaining an audioBuffer containing an audio clip, I proceed to create a visualization by drawing a series of sound bars in the shape of a circle: const { audioContext, analyser } = this.getAudioContext(); const source = audioContext.createBufferSou ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Static list elements are utilized in the CSS drop-down menu

It may appear that my coding skills are lacking or incorrect. When I attempt to create a drop-down menu in CSS, the new list elements end up on the other side of the page instead of within the container box. How can this be fixed? Below is the code snippe ...

jQuery Autocomplete - struggling to pinpoint the exact location where the width of the suggestions div is being defined

I have successfully implemented jQuery Autocomplete, but I am facing an issue with adjusting the width. Currently, it is set to 268px in Firebug, however, I would like it to be 520px. After checking the stylesheet, I couldn't locate where the width o ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

What is the most efficient method for exporting Express route functions for promise chaining?

Currently, I am in the process of refactoring an API route to utilize ES6 promises instead of callbacks, so as to avoid callback hell. Upon successful conversion to a promise chain, my intention was to extract the .then() functions into a separate file fo ...

PHP Email Request Denied with 500 Internal Server Error Response

I am currently working on designing a contact form for a website. I have implemented a jQuery .click() function for an HTML button and utilized ajax to invoke the email.php code. However, when I click the button, the console shows the error message: 500 ( ...

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Changing button alignment using CSS to create a new line

Currently, I am working on a React project using Material-UI where I am trying to create a numpad. The code snippet below showcases part of my implementation: // some parts are omitted for conciseness const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0]; ...