Last active
September 4, 2016 13:23
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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