I use this kind of ‘detecting’ to do my animation. I must mention that I have developed a class called ‘fadeInDown’ in my css before I have added this code, which contains the actual movement of the element. In my example, it fades in and drops down on full opacity. The code below only detects if a certain element is on our viewport and if it is, the code adds a class to it. Lets break that step by step:

Create a variable

Create a variable called ‘$animation_elements’ which selects every element with a class ‘$(‘.animation-element’)’. You can also use an ID, but because I am going to animate more than one element, I am working with classes.

Create a variable for window

We do the same for ‘$(window);’. By using the variable we trigger the function called ‘check_if_in_view’ everytime we resize the window or we scroll in any direction. This way, the function checks if the element in on view.

Create some more variables inside the function

The variables speak for themselves. We need these for the calculations which we are going to do after. So we have ‘window_height’ which is the height of your viewport. We have ‘window_top_position’ to find the top of the viewport and ‘window_bottom_position’ to find the bottom (we find this by simply adding the height of the viewport to the top). Then we need the same for each element which we are going to animate. Every ‘$animation_elements’ is passed to the function where we get the top, bottom and height of the element. Now the code knows where every element is on the page.

Check if the element is in view

The last step is finding if the element is visible or not. This is simply done by checking if the elements top is visible over the viewports bottom && if elements bottom visible on viewports top. If any of both conditions are returning true, then the animation class called ‘fadeInDown’ in my example, is added in. If they are not visible, the class will be removed and added when the viewport comes back. By this way, the element will always animate when the users scrolls over it.

Copy & paste the whole code

If you find my blogging useful, please share it.