SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Pull-to-Refresh

Pull to Refresh

Simulate pull-to-refresh by detecting a downward drag from the top of the page using touch events.

Example
let startY = 0;
const threshold = 80;
$(window).on("touchstart", e => { startY = e.originalEvent.touches[0].clientY; });
$(window).on("touchmove", function(e) {
  if (window.scrollY === 0) {
    const dy = e.originalEvent.touches[0].clientY - startY;
    if (dy > 0) {
      e.preventDefault();
      const pct = Math.min(dy / threshold, 1);
      $("#pull-indicator").css("opacity", pct).text(pct >= 1 ? "Release to refresh" : "Pull to refresh");
    }
  }
});
$(window).on("touchend", function(e) {
  const dy = e.originalEvent.changedTouches[0].clientY - startY;
  if (window.scrollY === 0 && dy >= threshold) reloadContent();
  $("#pull-indicator").css("opacity", 0);
});
Pro Tip

call e.preventDefault() to prevent the browser's native pull-to-refresh from triggering simultaneously.