A quick and powerful plugin for your pull-to-refresh needs in your webapp.

Overview

PulltoRefresh.js

Build Status NPM version CDNJS

PulltoRefresh.jsDemos

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


Donations

If you found this project useful, please consider making a donation.

Installation

Download PulltoRefresh either from the NPM Registry, CDNJS or UNPKG:

$ npm install pulltorefreshjs --save-dev
$ wget -O pulltorefresh.js https://unpkg.com/pulltorefreshjs

Include the JS file in your webapp and initialize it:

const ptr = PullToRefresh.init({
  mainElement: 'body',
  onRefresh() {
    window.location.reload();
  }
});

Bundlers can consume pulltorefreshjs as CommonJS and ES6-modules syntax:

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

API

  • 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).

Options

  • distThreshold (integer) Minimum distance required to trigger the refresh.
    — Defaults to 60
  • distMax (integer) Maximum distance possible for the element.
    — Defaults to 80
  • distReload (integer) After the distThreshold is reached and released, the element will have this height.
    — Defaults to 50
  • distIgnore (integer) After which distance should we start pulling?
    — Defaults to 0
  • mainElement (string) Before which element the pull to refresh elements will be?
    — Defaults to body
  • triggerElement (string) Which element should trigger the pull to refresh?
    — Defaults to body
  • ptrElement (string) Which class will the main element have?
    — Defaults to .ptr
  • classPrefix (string) Which class prefix for the elements?
    — Defaults to ptr--
  • cssProp (string) Which property will be used to calculate the element's proportions?
    — Defaults to min-height
  • iconArrow (string) The icon for both instructionsPullToRefresh and instructionsReleaseToRefresh
    — Defaults to ⇣
  • iconRefreshing (string) The icon when the refresh is in progress.
    — Defaults to …
  • instructionsPullToRefresh (string) The initial instructions string.
    — Defaults to Pull down to refresh
  • instructionsReleaseToRefresh (string) The instructions string when the distThreshold has been reached.
    — Defaults to Release to refresh
  • instructionsRefreshing (string) The refreshing text.
    — Defaults to Refreshing
  • refreshTimeout (integer) The delay, in milliseconds before the onRefresh is triggered.
    — Defaults to 500
  • getMarkup (function) It returns the default HTML for the widget, __PREFIX__ is replaced.
    — See src/lib/markup.js
  • getStyles (function) It returns the default CSS for the widget, __PREFIX__ is replaced.
    — See src/lib/styles.js
  • onInit (function) The initialize function.
  • onRefresh (function) What will the pull to refresh trigger? You can return a promise.
    — Defaults to window.location.reload()
  • resistanceFunction (function) The resistance function, accepts one parameter, must return a number, capping at 1.
    — Defaults to t => Math.min(1, t / 2.5)
  • shouldPullToRefresh (function) Which condition should be met for pullToRefresh to trigger?
    — Defaults to !window.scrollY • Please note that this default is useful whenever you're setting mainElement as the body of the document, if you need it in another element with overflow, use !this.mainElement.scrollTop. Refer to the multiple instances demo for reference.

Use with React

With ReactDOMServer and renderToString() you can use components as icons instead of just strings. In this example we also use Font Awesome to get nice icons with animation, but you can use any React component you like.

Demo on codesandbox.io

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;

Contribute

To quickly start the development workflow:

  1. Install NodeJS (NVM)
  2. Run nvm use 10 && npm install
  3. Then npm run dev

This will watch and compile the bundle for browser usage.

E2E tests are executed with Testcafé.

  • Run npm test to fire tests in the default browser, use BROWSER to change this
  • ...or just run make to setup the dependencies and run tests only (e.g. CI)

Advanced debug can be achieved with testcafe-live, e.g.

$ npm test --live chrome tests/e2e/cases --debug-on-fail

Roadmap

  • More events: onPullStart, onPullDown(direction, willRefresh), onRelease(willRefresh)
  • Fully customizable CSS
  • Gallery of use cases
  • Advanced demos
  • Tests
  • Minified releases
Comments
  • Refreshing when scrolling

    Refreshing when scrolling

    Hello, is there any way for me to perform the refresh only when I'm at the top of the page? As it stands the app reloads anytime I try to scroll down on the mobile web app.

    Thanks for any help.

    opened by jtmerch 13
  • Cannot read property 'classList' of null

    Cannot read property 'classList' of null

    When quickly slide the page, it may come across Cannot read property 'classList' of null or Cannot read property 'style' of null image

    I think the reason is the onReset function handler.ptrElement = null; handler.ptrElement is set to null ,but it is referenced in touchmove callback however.

    opened by pengfu 12
  • chrome defaults touch events as passive

    chrome defaults touch events as passive

    if you test out the demos in chrome you will see this in the console:

    Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
    

    https://www.chromestatus.com/features/5093566007214080

    states that chrome treats touch events as passive by default to avoid scroll delays.

    The fix would be to add the { passive: false } option to any addEventListener calls the could use preventDefault()

    opened by UziTech 9
  • How to display Pull To Refresh in overscroll Safari

    How to display Pull To Refresh in overscroll Safari

    When use scroll (touch) down and scroll up immediately in Safari (iOS device), it not detect should 'pull to refresh' and don't show the pull to refresh div.

    How can handle overscroll and show pull to refresh when user do it.

    Thank you

    opened by vukhacbiet 8
  • can not scroll in  chrome 74 or highter

    can not scroll in chrome 74 or highter

    Bug report

    Current behavior: in the chorme 74,the page I can slide down, but i can't slide up. And it is normal if i use chrome 66 or lower Expected behavior: the page can slide down or slide up JSFiddle URL for demo with bug: https://jsbin.com/wisiligeke/1/edit?html,js,console,output Browsers affected: mobile chorme 74

    opened by gdutwyg 7
  • Refresh when i swipe without being on top

    Refresh when i swipe without being on top

    I am trying to use this pull to refresh, but im having an issue. I've looked for other issues like this, but didnt found any answer that solve my problem, so I submited this issue. I tried with 0.1.14 and 0.1.17 versions and none worked. My app is built using cordova and i tested both in mobile and browser.

    Bug report

    Current behavior: When i scroll, my app refresh.

    Expected behavior: My app refresh only its on top.

    ** for demo with bug:** https://jsfiddle.net/L4dypo8n/

    Browsers affected: Google chrome / android

    opened by narcisao 7
  • Scroll up call refresh handler every time in multiple.html demo using 0.1.16

    Scroll up call refresh handler every time in multiple.html demo using 0.1.16

    Bug report

    In our mobile app, after upgrading from 0.1.14 to 0.1.16, the scrollbar will trigger the onRefresh handler every time users touch and drag up even though the view is not at the very top.

    I believe the code here makes trouble, the this.mainElement.scrollTop always return 0 each time scroll to be dragged up. However, using the old way, it works fine.

    shouldPullToRefresh: function shouldPullToRefresh() {
          return typeof this.mainElement === 'string' ? !document.querySelector(this.mainElement).scrollTop : this.mainElement && !this.mainElement.scrollTop;
          // return !window.scrollY
        },
    

    Current behavior: Calling refresh handler every time when scrolling up the page. Expected behavior: Not calling refresh handler when each time scroll up.

    JSFiddle URL for the demo with bug: This bug can be reproduced by tweaking the demo which is multiple.html, looks like the demo still using the old version, by replacing the pulltorefresh.js with the latest 0.1.16, the issue can be observed https://jsfiddle.net/bqc3jnds/ Browsers affected: Chrome dev tool in mobile mode and real devices

    opened by flying3615 7
  • 'onTouchMove' listener is causing issues after removing all listeners

    'onTouchMove' listener is causing issues after removing all listeners

    I'm experiencing an issue when I toggle between two pages in my app. The first page has the pull to refresh feature, the second page does not have this feature so when the user navigates to the second page, I invoke the destroy method to remove the listeners. But when I scroll on the second page, I get an error

    TypeError: Cannot read property 'classList' of undefined at _onTouchMove

    and all of my content disappears.

    opened by davidalee 7
  • Using v0.1.17 caused a heroku build to hang indefinitely.

    Using v0.1.17 caused a heroku build to hang indefinitely.

    Bug report

    I was working on a mobile web app in Rails and I found this package, which I think is fantastic by the way. I built my features on v0.1.17 and everything was fine in Dev and CI, but when deploying to Heroku the build hung then timed out. Normally I wouldn't bring this to your attention, but downgrading this package, the one from NPM btw, to v0.1.16 fixed my build.

    Let me know if you need more details, I can readily reproduce the problem.

    Current behavior:

    Building with Rails/webpacker/webpack on heroku hangs indefinitely on v0.1.17 from NPM but not v0.1.16.

    Expected behavior:

    Not hanging the webpack build

    JSFiddle URL for demo with bug:

    N/A

    Browsers affected:

    N/A

    opened by craigmcnamara 6
  • Customize the look

    Customize the look

    Hello,

    is it possible to customize the look of pulltorefresh.js? I like this library and it works very well, however I would like to have more of an Android look (see screenshot below) for a progressive web app that I am developing.

    image

    enhancement 
    opened by orck-adrouin 6
  • [WIP] Add test framework and basic tests

    [WIP] Add test framework and basic tests

    The goal with this PR is to setup and add a testing framework using Testem and QUnit and add some basic tests. I'm happy to incorporate any feedback/modifications that you think are needed

    Tests added:

    1. Basic test for init, it should add the expected style and ptr elements.
    2. Testing that the destroy() function removes the style and ptr elements.
    3. Init is idempotent and won't creating multiple style or ptr elements.

    I'd like to somehow write some tests for the event handlers. My thought is to export the functions alongside init() so that I can test them without having to actually trigger events. @pateketrueke, do you have any ideas on how to do this?

    opened by xcskier56 6
  • CSS animation runs whenever the state changes.

    CSS animation runs whenever the state changes.

    Bug report

    Current behavior: If you apply an animated style to iconArrow, the animation will continue to run whenever the state changes.

    Expected behavior: Users could want to add a custom animation style with the intent that the animation only occurs once (when pending -> pulling)

    JSFiddle URL for demo with bug: https://codesandbox.io/s/cranky-gates-ev74r4?file=/src/App.js

    Browsers affected: No dependency.

    opened by hanbin9775 1
  • `handler.destroy()` should remove ptr element immediately

    `handler.destroy()` should remove ptr element immediately

    Bug report

    When calling destroy or destroyAll then ptrElement might become visible for a short period of time when its styleEl is messed up (see https://github.com/BoxFactura/pulltorefresh.js/issues/119) due to it not getting removed from DOM immediately.

    Current behavior:

    When calling handler's destroy function then it does not remove ptrElement. It is being removed by onReset which might be called from multiple codepaths. However, in onReset a timeout is being used which in turn might cause a situation where ptrElement is removed from DOM after its handler's destroy has been called many cycles ago (default removal timeout is 500ms for example).

    Expected behavior:

    ptrElement should be removed immediately when _handler.destroy is been executed to avoid possible problems where handler has been destroyed and its element will be removed later by co-incidence by some timer.

    JSFiddle URL for demo with bug:

    N/A

    Browsers affected:

    Every browser

    opened by jarmo 0
  • destroyAll does not destroy all thus causing PullToRefresh misbehave when `styleEl` has been removed from DOM

    destroyAll does not destroy all thus causing PullToRefresh misbehave when `styleEl` has been removed from DOM

    Bug report

    Calling destroyAll keeps some state even though the word All implies that it's clean slate. For example it does not care about _shared.styleEl or _shared object contents at all which might cause problems.

    Fixes a problem reported previously in https://github.com/BoxFactura/pulltorefresh.js/issues/108

    Current behavior:

    Keeping global state between destroyAll and init might cause a problem where SPA type application is used and head is modified in the DOM in a way that PullToRefresh styleEl is removed from it, which is used internally by PullToRefresh.

    For example, I'm using a library called morphdom to patch head and body after fetch request and this also removes styleEl. It should not be a problem in itself because I'm also calling PullToRefresh.destroyAll() before patching and PullToRefresh.init() after patching the DOM.

    However, since PullToRefresh setupDOM function only checks if _shared.styleEl has a value, but does not care about the styleEl being part of the DOM. It just assumes that it is part of the DOM.

    A quick fix would be to change setupDOM to this:

    function setupDOM(handler) {
    ...
          if (!_shared.styleEl) {
            _shared.styleEl = document.createElement('style');
            _shared.styleEl.setAttribute('id', 'pull-to-refresh-js-style');
          }
    
          if (!_shared.styleEl.parentNode) {
            document.head.appendChild(_shared.styleEl);
          }
    
          _shared.styleEl.textContent = handler.getStyles().replace(/__PREFIX__/g, handler.classPrefix).replace(/\s+/g, ' ');
    ...
    }
    

    Basically we should check that styleEl is part of the DOM and if not then put it there.

    Expected behavior:

    Should even work when PullToRefresh internally used element for styling is removed from DOM.

    JSFiddle URL for demo with bug: N/A

    Browsers affected: Every browser.

    opened by jarmo 0
Owner
Box Factura
Tus facturas, en orden.
Box Factura
A native-like JavaScript pull to refresh implementation for the web.

Pull to Refresh for the Web 1.1 This is a pull to refresh implementation for the web. It focuses on buttery UX performance and responsiveness to feel

Andy Peatling 536 Dec 19, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Sachit Yadav 6 Nov 3, 2022
A quick and easy to use security reconnaissance webapp tool, does OSINT, analysis and red-teaming in both passive and active mode. Written in nodeJS and Electron.

ᵔᴥᵔ RedJoust A quick and easy to use security reconnaissance webapp tool, does OSINT, analysis and red-teaming in both passive and active mode. Writte

Dave 17 Oct 31, 2022
JOSE ZEPEDA 10 Nov 18, 2022
Clinton Mbonu 20 Jun 30, 2022
Refresh - Simple browser reload on file change middleware for your Deno web applications.

refresh Simple browser reload on file change middleware for your Deno web applications. Usage To use refresh middleware, just add a few extra lines to

Craig Morten 13 Dec 19, 2022
A leaderboard created using Leaderboard API service, Webpack, and Gitflow. The user can add a new score and refresh to see his ranking in the leaderboard.

Leaderboard A leaderboard created using Leaderboard API service, webpack, and gitflow. The user can add a new score and refresh to see his ranking in

ABDUL ALI 13 Dec 26, 2022
leaderBoard is a project used to add a score, view score list, and refresh score list. It is built using JS, HTML, BootStrap, and API.

LeaderBoard ?? Table of Contents ?? About the Project ?? Built With Tech Stack Key Features ?? Live Demo ?? Getting Started Setup Prerequisites Instal

Zewdie Habtie 4 Mar 20, 2023
This project is about Leaderboard list app, that allows users to add score to the list and refresh the list.

Leaderboard This project is about Leaderboard list app, that allows users to add score to the list and refresh the list. Built With JavaScript HTML CS

Mihreteab Misganaw 3 Dec 19, 2021
This project is built with JavaScript, Webpack, HTML & CSS, Leaderboard api. When user clicks on Refresh button it hits the api and responds with the data, The user can also post data to the api

leaderboad Description the project. this project is about the leaderboad i did during Microverse to build a website for adding Data to the API and fet

Emmanuel Moombe 4 May 30, 2022
Google Cloud Platform Refresh Token

Google Cloud Platform Refresh Token gcp-refresh-token is a cli util from plasmo to retrieve a refresh token as specified in Google's OAuth 2.0 Refresh

Plasmo 3 Jun 7, 2022
CLI tool to update caniuse-lite to refresh target browsers from Browserslist config

Update Browserslist DB CLI tool to update caniuse-lite with browsers DB from Browserslist config. Some queries like last 2 version or >1% depends on a

Browserslist 31 Dec 30, 2022
Flight is a universal package manager for your needs, no matter what language you may want to write your code in.

Flight Swift, reliable, multi-language package manager. ⚡ Installation We don't have an official release of Flight yet, however, if you would like to

null 26 Dec 25, 2022
To-do list" is an app that helps to organize your day. the user simply lists the things that needs to done and the app allows the to mark them as complete when they are done. Made with webpack, JavaScript ES6 , HTML 5 and CSS 3.

Todo-list project This is a Microverse project that entails a to-do-list. Built With HTML CSS Javascript Webpack VS code Live Demo (if available) Live

Youta Lactio Christabelle 10 Aug 3, 2022
This tool allows you to draw up plans for facilities from Foxhole's new Inferno update. It takes power and resource needs into account to help you efficiently design your facilities.

Foxhole Facility Planner This tool allows you to draw up plans for facilities from Foxhole's new Inferno update. It takes power and resource needs int

Brandon Ray 23 Dec 23, 2022