Advertisement
robwai

Function when in viewport

Oct 4th, 2022 (edited)
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 0.61 KB | None | 0 0
  1.  // Check to see if in viewport
  2. $.fn.isInViewport = function() {
  3.     var elementTop = $(this).offset().top;
  4.     var elementBottom = elementTop + $(this).outerHeight();
  5.  
  6.     var viewportTop = $(window).scrollTop();
  7.     var viewportBottom = viewportTop + $(window).height();
  8.  
  9.     return elementBottom > viewportTop && elementTop < viewportBottom;
  10. };
  11.  
  12. // if in viewport - Do this
  13. $(window).on('resize scroll', function() {
  14.     if ($('.animate').is(true) && $('.animate').isInViewport()) {
  15.         $('.animate').addClass('in-viewport');
  16.     } else {
  17.         $('.animate').removeClass('in-viewport');
  18.     }
  19. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement