colorful-tones
3/26/2015 - 3:59 PM

Simple wayfinder js to see if element is in viewport, and add classes or remove based on if it is.

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);