Skip to content

Instantly share code, notes, and snippets.

@davidpdrsn
Last active April 9, 2020 19:40
Show Gist options
  • Save davidpdrsn/4434085 to your computer and use it in GitHub Desktop.
Save davidpdrsn/4434085 to your computer and use it in GitHub Desktop.
Simple jQuery plugin used to determine if an element is within the viewport or not. It currently looks at the middle of the element.

What is this?

This is a simple jQuery plugin that detect whether or not an element is within the viewport.

How to use it

Simply calling $('.element').isInView() will return true if the middle of the element is within the viewport and false if not.

Example

$(window).on('load scroll', function() {
  if ( $('footer.main-footer').isInView() ) {
    // start animation within footer
  }
});
/*
* By David Pedersen (@davidpdrsn)
* https://gist.github.com/davidpdrsn/4434085
* Version 0.1
*/
jQuery.fn.isInView = function(){
// setup different vars for easier access to these values
var middle = Math.round(this.height() / 2),
winHeight = $(window).height(),
posTop = this.position().top,
scrollTop = $(window).scrollTop(),
middlePos = middle + posTop;
if ( middlePos < scrollTop ) {
// middle of element is above the viewport
return false;
} else if ( middlePos > scrollTop && middlePos < scrollTop + winHeight ) {
// middle of element is within the viewport
return true;
} else if ( middlePos > scrollTop && middlePos > scrollTop + winHeight ) {
// middle of element is below the viewport
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment