Calculating the vertical distance between an element and the top of the page

I am attempting to calculate the distance between the top of an element and the top of the page every time the user scrolls. Although I have managed to make it work, the issue arises when scrolling - the distance remains unchanged. I tried addressing this by implementing a closure, but my understanding of closures is limited. A demonstration of my progress can be found here: It logs the distances in the console.

I understand that there may be simpler solutions available, but I am eager to identify where I might be going wrong. Would anyone be able to assist me with this?

Below is the code I have been working on:

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8">
    <title>FitGrid</title>
    <link rel="stylesheet" href="fitgrid.css">
    <link rel="stylesheet" href="style.css">
</head>
<body>

<div class="container">

    <h1 class="fg12">Addison Bean.</h1>

    <div class="row">
    <h2>Article</h2>
    <hr class="fg6">
    <hr class="fg6 hidden">
    <p class="fg6">1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur, ut, saepe quia nam nesciunt delectus sequi incidunt quam amet eaque nostrum blanditiis laboriosam magni minima eveniet culpa dolore sit fugit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate, facilis, quo ab architecto veniam ducimus error porro molestiae numquam harum suscipit quae doloremque ullam libero consequuntur mollitia sit doloribus blanditiis. </p>
    <p class="fg6">2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate, facilis, quo ab architecto veniam ducimus error porro molestiae numquam harum suscipit quae doloremque ullam libero consequuntur mollitia sit doloribus blanditiis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur, ut, saepe qui...and so on
    </div>
    <div class="row">
    <p class="fg6">3. Another set of dummy text...</p>
    <p class="fg6">4. Yet another set of placeholder text...</p>
    </div>
    <div class="row">
    <p class="fg6">5. Additional filler for testing purposes.. .</p>
    <p class="fg6">6. More temporary content for layout checking...</p>
    </div>
    <div class="row">
    <p class="fg6">7. Continuation of test material...</p>
    <p class="fg6">8.Test text goes here...</p>
    </div>
</div>
<script>

    var elem = document.getElementsByTagName('h2')[0];
    function determineScrollOffset(el) {
        function getWindowOffset() {
        var woff = el.getBoundingClientRect().top,
            soff = window.pageYOffset;

        var dist = Math.round(woff + soff);
        console.log(dist);
    }

    return getWindowOffset;
}

window.onscroll = determineScrollOffset(elem);

</script>
</body>
</html>

Answer №1

Your solution in code form would look something like this:

let distance = Math.round(withOffset - startOff);

A live example can be found here

Answer №2

this method is quite effective in fetching the distance:

window.onscroll = function ()
{
    console.log(document.querySelector('h2').getBoundingClientRect().top);
}

it should be noted that a negative number indicates that the selected element is positioned above the top line of the viewport, while positive numbers indicate that it is below this line. A value of 0 signifies that the top of the element is perfectly aligned with the top line of the viewport.

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

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Extracting data from website's table using JavaScript and opening the link in href

My goal is to extract the details page for each link found on this particular page. The link provides access to all the information required: PAGE However, I'm interested in extracting details from pages that have links like this: href="javascr ...

Can you please explain the purpose of the state object in the setSearchParams hook of react-router-dom v6

Can anyone explain the { state: ? } parameter used in the update function of useSearchParams? const [search, setSearch] = useSearchParams(); setSearch( { ...Object.fromEntries(search), transFilters: JSON.stringify(filters), }, { ...

Manipulating the DOM using a Flask route in an HTML form

I have a form that allows users to input the names of "Player A" and "Player B". When the user clicks on the "Start Game" button, the game begins by redirecting to a Flask route (/players). I want the "player-text" section to be updated with the player nam ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Unable to utilize angular-local-storage

Here is the code snippet I'm working with: angular.module('MyModule').controller('MyController', ['$scope', '$stateParams','$location', '$http','LocalStorageModule', function($s ...

The upload directory fails to include the folder name when sending a file

After experimenting with the new directory upload feature, I encountered an issue where the server request did not preserve the exact folder structure as expected. Here is the HTML code snippet: <form action="http://localhost:3000/" method="post" enct ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Strategies for effectively managing numerous API requests

My current setup involves fetching about five API calls simultaneously. While it works at times, most of the time it results in a fetch error. Is there a way to prevent these errors from occurring when running the API calls? app.post("/movie/:movieN ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

Displaying received image using Express JS

Currently, I am working on managing two separate Express JS applications. One of them serves as an API, while the other application interacts with this API by sending requests and presenting the received data to users. Within the API route, I am respondin ...

The submit button in Angularjs does not respond to the Enter key press

Click below to submit: <input type="submit" ng-click="Showdata()" class="btn blue pull-right" Text="" /> Email input field: <input type="text" ng-model="texttype" class="form-control" ng-class="eml" placeholder="Enter Email" /> Password ...

Looking for a way to store data in a sub-document in MongoDB? I am having an issue where my farm sub-documents

After many attempts, I am still facing issues while saving farm data for a User. I created an API to sign up a user and save their data, including the farm object. However, every time I try to update the code, the farm object turns into null. The goal is t ...

Why don't inline style changes implemented by JavaScript function properly on mobile browsers like Chrome, Dolphin, and Android?

View the jsFiddle here Issue on PC/Windows browser: When performing action, h1 header "gif" disappears and video starts playing. Problem on mobile devices: The gif does not disappear as expected but the video still plays indicating that JavaScript is fun ...

Show an HTML email message on a webpage without disrupting the existing page layout

Looking for a solution to display mail messages on a web page originating from an exchange server with various style elements that might interfere with the existing page layout. Attempting to load these mail messages within a div results in the style elem ...

Using AngularJs, you can access the document.body.onfocus event within the controller of

I am attempting to detect when the user closes or cancels the File Upload Window <input type="file"> Since there isn't a built-in listener for the close event of the file upload, I am trying to capture it using the document.body.focus event, s ...

Updating the Ajax Url dynamically while scrolling

I am trying to update the Ajax URL dynamically, and here is my progress so far: var size=1; var from = 1; window.addEventListener('mousewheel', function(e){ if(e.wheelDelta<0 && from<5){ from++; } else if(e.whe ...

Place the `service` parameter into the `run` function

What are some examples of when to utilize the angular.run method? I have a service that is resource-intensive and takes a significant amount of time to initialize before it can be used in conjunction with my view. angular.module('myApp').service ...