Skip to content

Instantly share code, notes, and snippets.

@lukewhitehouse
Last active September 10, 2015 11:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukewhitehouse/676d6dfcbc9aeeafd767 to your computer and use it in GitHub Desktop.
Save lukewhitehouse/676d6dfcbc9aeeafd767 to your computer and use it in GitHub Desktop.
Check for if an element is in view

Check for if an element is in view

This script allows you to tell when an element becomes visible in the browser window. You can use this to apply styling/animations to elements.

Instructions

Add this to your javascript. Make sure jQuery is called before this script.

Requirements

  • jQuery
function getPositionInfo(elem) {
var pos = {};
pos.docViewTop = $(window).scrollTop();
pos.docViewBottom = pos.docViewTop + $(window).height();
pos.elemTop = $(elem).offset().top;
pos.elemBottom = pos.elemTop + $(elem).height();
return pos;
}
$(window).scroll(function () {
$('.awesome').each(function () {
var pos = getPositionInfo(this);
if(pos.elemTop <= pos.docViewBottom) {
$(this).addClass('inview');
} else {
return false;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment