When the div reaches the top of the viewport window, call this function

Can you review the code snippet below?

I need a function to trigger when the red box's top aligns with the viewport during scrolling.

JS Fiddle: http://jsfiddle.net/ay5ttmLk/

HTML
<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
</div>


<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
sadfsaf
sadfsafsadf
</div>

CSS
.test {margin-top: 500px;
margin-bottom: 1000px;
background-color: red;}

JS
var el = $('.test');
el.on('scroll', function(){
if(el.scrollTop() == 0){alert("hit the top")}
});

Answer №1

Take a look at this unique fiddle.

I've included code that triggers an alert whenever the .test div reaches the top (multiple times). If you only want the alert/code to be executed once, then simply remove the else part.

Here's the modified code:

$(document).ready(function() {
  $('.test').attr("attop", false);
  var lastScrollTop = 0;
  $(window).on('scroll', function() {
    var windowScrollTop = $(this).scrollTop();


    if (windowScrollTop > lastScrollTop) {
        var currentDiv = $('.test[attop="false"]:first');
        if (currentDiv && currentDiv.length > 0) {
            if (windowScrollTop >= currentDiv.offset().top) {
                currentDiv.attr('attop', true);
                alert('reached top');
            }
        }

    } else {//this part needs to be removed to call only once
        var currentTopDivs = $('.test[attop="true"]');
        if (currentTopDivs && currentTopDivs.length > 0) {
            $.each(currentTopDivs,function(i,elem){
                if (windowScrollTop <= $(elem).offset().top) {
                    $(elem).attr('attop', false);
                }                   
            });
        }
    }
    lastScrollTop = windowScrollTop;

  });
});

I hope this helps you achieve your goal.

Answer №2

It seems like there isn't a straightforward way to determine if an element is at the top of the viewport (as opposed to the top of the document). However, you can perform a manual check to verify this:

$(window).on('scroll', function() { 
    var topViewport = $(window).scrollTop();
    // There are 2 issues here
    // - Your 'el' variable is an array with two elements. You need to specify which one you want to check or add an extra condition
    // - Using scrollTop on an element does not give accurate results. Try using offset().top instead
    var topElement = $(".test").eq(0).offset().top; 

    // Perform a small check (is the gap less than 100?) to consider it at the top.
}

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

Displaying data from a JSON object to a DOM table can be achieved by dynamically generating table columns based on the keys within

There is a JSON object that I'm working with: [ { "SysID": "4", "Defect Classification": "Wrong Image Color", "1": "3.0", "2": "", "3": " ...

Removing various data entries based on timestamp and additional fields in Firebase Firestore

I stumbled upon a similar query before. Being new to coding, I am attempting to remove all documents in the "users" collection that are older than 1 month and not marked as premium. The deletion criteria involve checking if the "user_online" field is at le ...

What is the best way to pass an array to a JavaScript function from a different page?

My website has a static settings page where my JavaScript function uses AJAX to retrieve data from a MySQL table and display it in a table on an HTML document. It's working perfectly, gathering all the necessary data efficiently. Here's the code ...

Is it possible to update the content page without having to refresh the master page?

Our website features a Master page with main menu options and corresponding sub menus. When a user clicks on a main menu item, the relevant sub menus should be displayed. After clicking on a sub menu, the content page should update without having to refr ...

"Trouble with server communication: data array not being passed to hbs

In my GET route, I have the following: app.get(("/employee/:id"), (req, res) => { data.getEmployeeByNum(req.params.id).then((data) => { res.render("employee", {employee: data}); }).catch(function(reason) { res.render("employe ...

Pattern for either one or two digits with an optional decimal point in regular expressions

Currently, I'm utilizing for input masking. I am specifically focusing on the "patterns" option and encountering difficulties while trying to create a regex expression for capturing 1 or 2 digits with an optional decimal place. Acceptable inputs: ...

Having trouble with the Material-UI v1 Drawer component on the iOS 13 beta version

As we prepare for the upcoming iOS release, set to debut next month, it has come to our attention that the main navigation on our website is experiencing issues when accessed using an iOS device running the latest beta (iOS13). While the drawer opens as ex ...

Organize files into pairs using array fields in Mongo Aggregation

Is there a way to organize the date field in each document sequentially? { _id: ObjectId('...'), date: [ISODate('2022-05-27T00:00:00.000+00:00'), ISODate('2022-05-28T00:00:00.000+00:00') ...] } The expected format for the ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Javascript continues to execute even after the designated element has been eliminated or substituted

I'm currently working on a WordPress auction site using WooCommerce that needs a countdown timer to display when a specific product auction is ending. Below is the JavaScript code for the countdown timer: const getElem = elem => document.q ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Discover an array by analyzing the variable's value

I am working with an array called login which contains the values "login" and "php". I also have a variable named withoutNumberSign that is determined by the URL, and in this instance should be set as login. How can I access the elements of the login arr ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

What is the best way to transfer information from a client to a server using Meteor?

I am currently developing an application and have encountered an issue. I have an HTML page located in the './public' folder. Within the './public/js' directory, there is a script that gathers data after a form is submitted on this page ...

What steps do I need to take to ensure that Phaser implements modifications made in my game.js file?

I recently completed the Phaser Tutorial and set up my project with an index.html file and a game.js file, along with downloading the phaser.min.js file. All files are located in the same folder. Although I have connected everything correctly and the outp ...

Rotating Effects with jQuery and CSS

I am on the lookout for a jQuery Plugin or a method to achieve this specific animation using CSS transforms. https://i.sstatic.net/L2hjD.png Despite my efforts with Google, all I came across was the typical flip animation. However, I am looking for one t ...

The error message in Next.js states: "Attempting to access properties of undefined (specifically trying to access 'indexOf')."

After successfully running the code below, I encounter an issue upon refreshing the page: TypeError: Cannot read properties of undefined (reading 'indexOf'). const [folders, setFolders] = useState([]); const [user] = useAuthState(auth); c ...

Using Rails to render a partial with a JSON object

In my rails app, there is a javascript callback that runs after a post is created. This callback polls a processing endpoint to check if an image has finished processing and then updates the view accordingly: create.js.erb create callback // initiating t ...

issue with retrieving HTML data from PHP and converting it to JSON

I've tried multiple search queries but nothing seems to be working. Can someone please assist me? ----------jQuery Function ---------------------------- function showRequestFunctionToBox(thisId){ var encodedItemId = thisId; ...

Top strategies for effectively handling Bootstrap in Python Flask projects

After putting in the effort to develop a web app using python-Flask and bootstrap for the frontend, I am excited to share my project that enables users to conveniently browse the AWS S3 bucket directly from their web browser. As this project is still a wor ...