Skip to content Skip to sidebar Skip to footer

Function To Be Called Once Div Hits Top Of Viewport Window

Wondering if you could have a look at the below code. Im wanting a function to be called once the top of the red box hits the top of the viewport on scroll. JS Fiddle: http://jsfi

Solution 1:

Check this fiddle.

I have added code to alert whenever .test div reaches at top (multiple times). If you need to call the alert/some code only once then you need to remove else part.

Below is the 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 oncevar 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;

  });
});

Hope this is what you are trying to achieve.

Solution 2:

I don't think there is a way to check of top viewport (there is top of document). However, you can do a manual test to check it:

$(window).on('scroll', function() { 
    var topViewPort = $(window).scrollTop();
    // You have 2 problems here// - Your el is an array with two elements. You have to specify which one you want to check or add extra condition// - scrollTop on the element doesn't mean anything. You need to use offset().top to get the datavar topElement = $(".test").eq(0).offset().top; 

    // Do small check (gap length < 100?) to consider it on top.
}

Post a Comment for "Function To Be Called Once Div Hits Top Of Viewport Window"