Skip to content

Instantly share code, notes, and snippets.

@lukewhitehouse
Last active Sep 10, 2015
Embed
What would you like to do?
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