Sometimes it can be useful to know what the distance is in pixels, from the top of an element to the top of the window. For example I recently had to integrate an SVG animation into a page, the main feature being the initial animated entrances of the various elements that made up the SVG.

The animation needs to fire only once, and after the page has been loaded of course. However, because it had to be located someway below the fold line, I needed to know what the distance was from the top of the SVG container to the top of the window as the user scrolled, then trigger the animation once it was in view.

What I actually need to do here is to define a distance or threshold really, the distance being from the top of the container to the top of the window, then if the user has scrolled past that point the animation would fire. Keeping in mind that I only want to fire the animation once; I don’t want to do this every time the user scrolls past the threshold.

To start with I created a generic convenience function, which can be passed a jQuery selector, in this case the container ID for my SVG.

Using the convenience function above I can now get the distance from the top of the div containing my animation, to the top of the window, as the user scrolls the page:

With this now working nicely, I can now use my function to complete the solution, note the flag distanceThresholdReached. – Additionally, something that I almost overlooked, I also need handle the scenario if the page has been refreshed at the location of the SVG.

The full solution above is of course tailored to the specific needs of my SVG animation, however the concepts here can be applied to many situations.

Tutorial

LEAVE A COMMENT

Notify of
avatar
wpDiscuz