Skip to content

Instantly share code, notes, and snippets.

@colorful-tones
Last active September 4, 2016 13:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colorful-tones/013fe199bd743660d644 to your computer and use it in GitHub Desktop.
Save colorful-tones/013fe199bd743660d644 to your computer and use it in GitHub Desktop.
Simple wayfinder js to see if element is in viewport, and add classes or remove based on if it is.
// check if element is in viewport
// if so, then add/remove class
// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433
(function($) {
// function to check if element is in viewport
function inViewport(element) {
if (typeof jQuery === "function" && element instanceof jQuery) {
element = element[0];
}
var elementBounds = element.getBoundingClientRect();
return (
elementBounds.top >= 0 &&
elementBounds.left >= 0 &&
elementBounds.bottom <= $(window).height() &&
elementBounds.right <= $(window).width()
);
}
// function to add/remove class to element if it is in viewport
function addClassToElementInViewport(element, newClass) {
if (inViewport(element)) {
element.addClass(newClass);
} else {
element.removeClass(newClass);
}
}
// function to add/remove class to a specified element based on whether
// another specified element is in viewport
function addClassToDifferentElementInViewport(element, differentElement, newClass) {
if (inViewport(element)) {
differentElement.addClass(newClass);
} else {
differentElement.removeClass(newClass);
}
}
// Example usage:
// check when window loads, resizes, or scrolls and call desired function
$(window).on('load resize scroll', function() {
addClassToElementInViewport($('.my-coolio-thing'), 'animate-bug-icon');
addClassToElementInViewport($('.another-thing'), 'animate-thing');
addClassToDifferentElementInViewport($('.animated-thing'), $('.another-animated-thing'), 'stop-animating-another-animated-thing');
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment