Friday, September 21, 2018

jQuery: Function to check when element is (visible) in viewport

Here's the function
//function to check when element is in viewport
function isScrolledIntoView(elem){
    var $elem = $(elem);
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
Example usage:
$(window).scroll(function(){
  $('.ar-yellow-arrows-wrap').each(function(){
    if(isScrolledIntoView($(this))){
      $(this).addClass('m-fwd');
    }
    else{
      $(this).removeClass('m-fwd');
    }
  });
});

No comments:

Post a Comment