pull on refresh

by Axelvaisper

HTML

<meta name="viewport" content="width=device-width">
<div class="refresh"></div>
<div class="container">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce in nisi et turpis dapibus imperdiet elementum suscipit ante. Duis ut nisl ullamcorper urna pretium pretium ac at diam.
</div>

CSS

body {
    font: 100% sans-serif;
    margin: 0;
}

.refresh {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #efefef;
    padding: 2em 0;
    text-align: center;
    z-index: -1;
}

.refresh:not(.loading)::after {
    content: "↓";
}

.loading::after {
    content: "Refreshing...";
}

.container {
    position: relative;
    background-color: #eee;
    height: 50em;
    box-shadow: 0 0.5em 0.5em 0.5em rgba(0, 0, 0, 0.2);
    padding: 1em;
}

JavaScript

var maxHeight = 85,
    height = 1,
    $container = $(".container"),
    $refresh = $(".refresh"),
    touchY = 0,
    curY = 0;

$(window).on({
    "touchstart": function (e) {
        if ($(this).scrollTop() === 0) {
            $container.toggleClass("dragging", true);
            touchY = e.originalEvent.changedTouches[0].clientY;
        }
    },
    "touchend": function () {
        $container.toggleClass("dragging", false);
        
        if (height >= maxHeight) {
            $.ajax({
                url: "/echo/html/",
                data: {
                    html: "Ajax loaded content.",
                    delay: 1
                },
                success: function () {
                    $container.text("Loaded").animate(
                        {top: 0},
                        function () {
                            $refresh.toggleClass("loading", false);
                        });
                }
            });
        } else {
            $container.animate({top: 0});
        }
        
        height = 0;
    },
    "touchmove": function (e) {
        var pullDown = !!(height-maxHeight);
        if ($container.hasClass("dragging") && height >= 0 && height < maxHeight) {
            curY = e.originalEvent.changedTouches[0].clientY;
            height = curY-touchY;
            $container.css("top", height);
        }
        if (height >= maxHeight) {
            $refresh.toggleClass("loading", true);
        }
    }
});