How to create a pull-to-refresh effect in websites similar to mobile apps

How to create pull-to-refresh effect in websites similar to mobile apps

Creating a pull-to-refresh effect on websites, similar to what’s commonly found in mobile apps, involves a combination of HTML, CSS, and JavaScript.

Introduction

In today’s era, everyone needs a responsive website. This means a site should work on all devices (desktops, tablets, and mobiles). People nowadays mostly use mobile phones to open websites. If you are creating a web app or if you want web users to get mobile app-related features when they open a website on their phones, you need to add some gestures that a mobile app usually has. One of the gestures that you can add is to create a pull-to-refresh effect on the website. When a user opens the website and tries to refresh it they will get a very similar and known user experience.

JavaScript is a great language that allows us to add interactivity to the website. We can use JavaScript to add many other gestures to the website.

One of the best methods to enable the pull-to-refresh effect is to use PullToRefresh.js JavaScript library.

Implement pull-to-refresh effect using PullToRefresh.js?

A small, but powerful Javascript library crafted to power your webapp’s pull to refresh feature. No markup needed, highly customizable and dependency-free!

PullToRefresh

The PullToRefresh.js comes with 3 stages; when an action is triggered:

pull-to-refresh effect-pull-to-refresh-stage-1
Pull to refresh stage 1

When action is in the process (during refresh):

pull-to-refresh-stage-2
Pull to refresh stage 2

The last stage is when the action is completed.

Why use PullToRefresh.js

We have used pulltofresh.js to achieve the pull-to-refresh effect because of the following features:

  • Plug & play: very easy to use
  • Markup-agnostic
  • Easy to customize: tons of methods
  • Lightweight: fast to load
  • Dependency-free: simple and robust
  • Open source

How to use PullToRefresh.js

The PullToRefresh.js comes with an npm package as well as a CDN link.

NPM Package

Open the terminal and execute the following command:

npm install pulltorefreshjs --save-dev

or

wget -O pulltorefresh.js https://unpkg.com/pulltorefreshjs

CDN Installation

The library is available as a CDN link:

<script src="https://cdnjs.cloudflare.com/ajax/libs/pulltorefreshjs/0.1.22/index.umd.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The latest version at the time of writing this article is 0.1.22.

Prerequisites

Before diving into the code for pull-to-refresh effect implementation, make sure you have a basic understanding of HTMLCSS, and JavaScript. Ensure you have a text editor like Visual Studio Code or Sublime Text installed for a seamless coding experience.

Setting Up the HTML Structure

Let’s start by creating the HTML structure for our calculator. Open your preferred code editor such as Visual Studio Code or Sublime Text and create a new HTML file say index.html. Execute PullToRefresh.js like the following and pass an element selector. A simple HTML example:

<!DOCTYPE html>
<html class="no-js" lang="en"><head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PullToRefresh.JS</title>
  <!-- some basic css for styling -->
  <style type="text/css">
    body {
      font-family: arial;
    }
    h1 {
      font-size: 28px;
      color: red;
    }
    p {
      font-size: 16px;
    }
  </style>
</head>
<body>
  <!-- main wrapper -->
  <div id="main">
    <h1>PullToRefresh.JS Demo</h1>
    <hr/>
    <p>Pull-to-refresh effect. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>

  <!-- include  pulltorefresh.js -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pulltorefreshjs/0.1.22/index.umd.min.js"></script>
  <script>
    // initialize
    PullToRefresh.init({
      mainElement: '#main',
      onRefresh: function() { 
        // on refresh code goes here
        alert('refresh') 
      }
    });
  </script>
</body>
</html>

The above HTML example uses CDN links.

The React JS Example

It can also be included as the ES6 module:

import PullToRefresh from 'pulltorefreshjs';
// or
const PullToRefresh = require('pulltorefreshjs');

A full React JS example is:

import React, { Component } from 'react';
import ReactDOMServer from 'react-dom/server';
import PullToRefresh from 'pulltorefreshjs';
import { faSyncAlt} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

class App extends Component
{
    componentDidMount()
    {
        PullToRefresh.init({
            mainElement: 'body',
            onRefresh() {
                window.location.reload();
            },
            iconArrow: ReactDOMServer.renderToString(
                <FontAwesomeIcon icon={faSyncAlt} />
            ),
            iconRefreshing: ReactDOMServer.renderToString(
                <FontAwesomeIcon icon={faSyncAlt} spin={true} />
            ),
        });
    }

    componentWillUnmount()
    {
        // Don't forget to destroy all instances on unmout
        // or you will get some glitches.
        PullToRefresh.destroyAll();
    }

    render()
    {
        return (
            <div>
                <h1>App</h1>
            </div>
        );
    }
}

export default App;

API Properties

Following are the API options available to configure the PullToRefresh.js:

APIDetails
init(options)Will return a unique ptr-instance with a destroy() method.
destroyAll()Stop and remove all registered ptr-instances.
setPassiveMode(isPassive)Enable or disable passive mode for event handlers (new instances only).
Reference: Options

Method Properties

Following are the method options available to configure the PullToRefresh.js:

OptionDefaultDescription
distThreshold60(integer) Minimum distance required to trigger the refresh.
distMax80(integer) Maximum distance possible for the element.
distReload50(integer) After the distThreshold is reached and released, the element will have this height.
distIgnore0(integer) After which distance should we start pulling?
mainElementbody(string) Before which element the pull to refresh elements will be?
triggerElementbody(string) Which element should trigger the pull to refresh?
ptrElement.ptr(string) Which class will the main element have?
classPrefixptr– (string) Which class prefix for the elements?
cssPropmin-height(string) Which property will be used to calculate the element’s proportions?
iconArrow&#8675;(string) The icon for both instructionsPullToRefresh and instructionsReleaseToRefresh
iconRefreshing&hellip;(string) The icon when the refresh is in progress.
instructionsPullToRefreshPull down to refresh(string) The initial instructions string.
instructionsReleaseToRefreshRelease to refresh(string) The instructions string when the distThreshold has been reached.
instructionsRefreshingRefreshing(string) The refreshing text.
refreshTimeout500(integer) The delay, in milliseconds before the onRefresh is triggered.
getMarkup(function) It returns the default HTML for the widget, __PREFIX__ is replaced.
getStyles(function) It returns the default CSS for the widget, __PREFIX__ is replaced.
onInit(function) The initialize function.
onRefreshwindow.location.reload()(function) What will the pull refresh trigger be? You can return a promise.
resistanceFunctiont => Math.min(1, t / 2.5)(function) The resistance function accepts one parameter and must return a number, capping at 1.
shouldPullToRefresh!window.scrollYfunction) Which condition should be met for pullToRefresh to trigger?
Reference: Options

Click here to learn more about the PullToRefresh.js library.

Conclusion

The example sets up a basic pull-to-refresh effect. You can customize the styles and modify the JavaScript code to suit your specific requirements. Additionally, you may want to replace the simulated data loading logic with your actual data fetching mechanism.

Related Posts