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.

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

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.

Leave a comment

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

You can also subscribe without commenting.