Pull to refresh animation with Vanilla JavaScript

Vijit Ail
Level Up Coding
Published in
4 min readMay 12, 2019

--

Photo by Daria Shevtsova from Pexels

Pull-to-refresh is a very popular swipe gesture on smartphones that allow users to load new content on top of lists of data. It is used in most popular apps for smartphones and as well as in web apps and has become a major part of UX.

https://codepen.io/Vijit_Ail/full/pmbypw (Open the devtools to try out the animation)

A few days ago I came across the animation above on dribbble, so I thought I would come up with my version of it.

Guess what, I managed to build this with no libraries or jQuery plugins, just plain Vanilla JavaScript. 😎

A very simple markup for it — a top loading container that will contain the loader and a bunch of cards.

Let’s get to the fun stuff now 😁.

The idea is to hide the loading container by default and slide it down when the user swipes down.transform-style : preserve-3d will enable the cards to be positioned in 3D space and the perspective property on the card wrapper will determine how the user will see from their perspective; lower values will produce more intense 3D effects. Note that perspective is not set on the child elements. More about CSS 3D animations and transforms.

That was all the CSS that we need. Now let’s begin adding the swipe gesture.

Touch events in JS are handled by the touch event listeners. These are similar to mouse events except they allow multiple touches on the touch surface.

pStart and pCurrent objects will store the touch positions of the start and current touch. We’ll require these to find the change in the Y coordinate to calculate the rotation of the cards.

In the swipeStart() function, we’ll capture the touch coordinates and assign it to the pStart object.

In the swipe() function, we are setting the pCurrent object with current touch coordinates. The next step is to find the difference between the start and current Y position to calculate the distance of swipe and make a rotation based on 30% of the distance. The loading container will only appear if the distance is greater than 100.

The swipeEnd() function will undo the rotation if the touch has begun but has not enabled the loading.

While loading, the loading container will slide down for 2 seconds for the purposes of this demonstration, but in a real-world example, it can take more or less time based on the response from the server. The loading container and cards will move back to the original state once the loading has finished.

I took reference for JavaScript from this stackoverflow question.

The complete source code in my codepen. Open the devtools to see the animation in action.

I hope you got to learn something new today 😄. If you have any questions or have any suggestions for improving the code, feel free to write your response.

Cheers and happy coding 🍻 ✌

--

--