Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Created February 6, 2018 14:09
Show Gist options
  • Save jagdeepsingh/ed7cbccf2be9c3556601af72ed20b884 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/ed7cbccf2be9c3556601af72ed20b884 to your computer and use it in GitHub Desktop.
JavaScript, jQuery - Check element position with respect to Viewport
// @params
//   element - Element whose position is to be found
//   footerHeight - Height to subtract from window bottom in case of a fixed footer/overlay
window.elementPositionByViewport = function(element, footerHeight) {
  var elementBottom, elementTop, screenBottom, screenTop;

  if (footerHeight == null) {
    footerHeight = 0;
  }

  elementTop = $(element).offset().top;
  elementBottom = elementTop + $(element).outerHeight();

  screenTop = $(window).scrollTop();
  screenBottom = screenTop + window.innerHeight;
  screenBottom -= footerHeight;

  if ((screenBottom > elementTop) && (screenTop < elementBottom)) {
    return 'visible';
  } else if (elementTop < screenTop) {
    return 'above';
  } else {
    return 'below';
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment