[Solved] Function to be called once div hits top of viewport window


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 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;

  });
});

Hope this is what you are trying to achieve.

solved Function to be called once div hits top of viewport window