John Russell Blog

JavaScript Scroll Into View

There are times when you may want to add interactivity to your website based on the scroll position relative to an elements position but don’t want to use yet another jQuery plugin. This can be useful to check to see if an element has scrolled into view. So, below I’ve added a very simple function that accepts a jQuery selector string as its only parameter and then returns an object that contains position information about the desired element. All position attributes are boolean values so they can easily be used with conditional logic. The first is “visible” which will be set to true if the desired element is currently visible on the screen (partially or wholly). The second is “above” which will be set to true if the desired element is currently above what is visible on the screen. The last is “below” which will be set to true if the desired element is currently below what is visible on the screen.

function elementVisible(element) {
	var returnValue = {};
	var docViewTop = $(window).scrollTop();
	var docViewBottom = docViewTop + $(window).height();
	var elementTop = $(element).offset().top;
	var elementBottom = elementTop + $(element).height();
	    
	returnValue.visible = ((elementBottom >= docViewTop && elementBottom <= docViewBottom) || (elementTop <= docViewBottom && elementTop >= docViewTop) || (elementTop <= docViewTop && elementBottom >= docViewBottom));
	returnValue.above = (elementBottom < docViewTop);
	returnValue.below = (elementTop > docViewBottom);
	    
	return returnValue;
}

This function can easily be used in combination with a the jQuery scroll method.

(function($) {
	var myDesiredElementVisibility;
	
	$(window).scroll(function(e) {
		var myDesiredElementVisibility = elementVisible('#my-desired-element');
		if (myDesiredElementVisibility.visible) {
			// Element is visible
		}
		if (myDesiredElementVisibility.above) {
			// Element is above the view
		}
		if (myDesiredElementVisibility.below) {
			// Element is below the view
		}
	});
})(jQuery);

As you can see it’s easy to check if an element has scrolled into view by checking if it’s visible, above, or below the view. This could be used to add or remove classes to an element, and perhaps used to set an elements position to be fixed. There are jQuery plugins, such as ScrollMagic, which provide many more features and allow for much more complex interactivity, but for simple scroll based interactions the above function is quite useful.

As always please use the comments area to share your thoughts or suggestions for improvement.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *