Retrieving a single number from Jquery's offset function during scroll events

Seeking the Current Top Position of Web Page Elements

In my web page, I have divs with a height of 100%, each containing different content. I am attempting to determine the top position of these divs to manipulate them accordingly. However, when I try to do so, the function returns a single number that does not change as I scroll.

This is snippet of my code:

HTML:

<header id="header">
   <div id="menu-div" class="container-full">
        <div class="container">
            <a href="#">TEST</a>
            <a href="#">TEST</a>
            <a href="#">Test</a>
            <a href="#">Test</a>
            <a href="#">Test</a>
            <a id="request-demo-a" class="pull-right" href="#">TEST demo</a>
            </div>
        </div>
   </header>


   <div id="first-div" class="center a-div">
   test content...
   </div>


   <div id="full-div" class="container a-div">
        test content...
        </div>

  <div id="other-div" class=" a-div">
    More test content here...
  </div>



  <div id="other-div" class=" a-div">
    Even more test content here...
  </div>

CSS:

.a-div{
    height:100%;
}

#full-div{
    position:absolute;
    top:100%;
    width: 100%;
    height: auto;
    background: white;
    z-index:5;
}

...

JavaScript (Jquery):

$(function(){
        /**start:Scroll*/
        $(document).scroll(function(){
         $("#request-demo-a").html($('#full-div').offset().top);
         /// I want this return current value of full-div!
         //And when it become equel 0 do something! (This is just example)

        });
        /**End: Scroll*/      
})

JSFiddle-Demo

I am aiming to obtain the position of #full-div and trigger certain actions based on its value, such as executing a function when it reaches the top edge. Why is $('#full-div').offset().top returning a static number instead of updating while scrolling?

Answer №1

As you scroll, the position of an element remains the same with the offset() method, as it is relative to the document and not affected by scrolling. To track the distance scrolled, you can use scrollTop and compare it to the element's offset to determine if it has reached the top of the document.

$(document).on('scroll', function(){

    var scrolled = $(window).scrollTop();
    var offset   = $('#full-div').offset().top;

    if ( offset <= scrolled ) {
       // Perform action when element reaches or passes top of page
    }

});

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

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Reducing image file sizes in Ionic 3

I have been struggling to compress an image client-side using Ionic 3 for the past couple of days. I have experimented with: ng2-img-max - encountered an error when utilizing the blue-imp-canvas-to-blob canvas.toBlob() method (which is a dependency of ng2 ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

Validation in ASP.Net to ensure the correct number of days between the arrival and departure dates

One of my project requirements involves checking the validation of the number of days entered between two date selectors (From & To Dates). The constraint is that the difference should not exceed 100 days. I'm considering using ASP.NET validators for ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Issue with displaying YouTube videos in HTML causing them to be downloaded instead of playing

I'm currently facing an issue with loading a video on my HTML page using the following code: <video v-for="(data, key) in projectData.videos" :key="key" width="320" height="240" controls> <source :src="data.url"> </video> One ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...

Stop users from submitting likes or dislikes more than once

JavaScript Logic $('button.like').click(function(){ $.get($(this).parent().attr('href'),function(data){ $(this).html(''+data); }); return false; }); View Function def like(request): if request.is_aj ...

Concealing a Specific Element with Text using jQuery

Is there a way to conceal the section that includes the element labeled as "Product Tags" on a webpage? ...

Error: $controller does not function as a controller within another controller

I recently started learning Angular JS and attempted to call one controller within another, but encountered the following error: ionic.bundle.js:21157 TypeError: $controller is not a function at new <anonymous> (http://localhost:8080/itravel/www/js/ ...

Is there a way to sort an elastic query using JavaScript?

I'm trying to modify my elastic query by adding and removing items from an array. In the array below, I want to remove the element that contains 'item2'. How can I achieve this by checking if the key 'item2' exists and then deletin ...

Error: The database connection is currently down

Hey there! I'm currently working on a school project and running into some issues with inserting data into the database. I can't figure out what I'm doing wrong. There are no errors showing up, but for some reason, the information I input i ...

The Power of the CSS Universal Selector and Specificity

Currently exploring the puzzling scenario where .x seems to have higher specificity than *.x, despite expectations. Shouldn't *.x technically have a specificity of 0-0-1-1 (1 class, 1 tag) while .x is just one class with specificity 0-0-1-0? Let&apo ...

Understanding the flattening process of arrays using JavaScript - Detailed explanation required

Currently, I am immersed in the captivating world of Eloquent JavaScript. However, I have hit a roadblock with one of the exercises that involves flattening a multi-dimensional array. Despite my best efforts, I have been unable to crack the code. After f ...

Is there a way to retrieve an array generated within a JavaScript loop?

I've been working on retrieving column values from a database and storing them in an array, but I keep getting an empty array as the result. function FetchData(query, db) { var resultArray = new Array(); db.transaction(function(tx) { tx.executeSq ...

The functionality of Angular.js ajax and apply is experiencing technical difficulties

As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...