//grab the list var list = document.getElementById("touchlist"); //grab the loading div var loader = document.getElementById("touchloader"); //keep the state whether the fingers are touched var isTouched = false; //keep the state whether a PULL actually went out var isMoved = false; //This has the original Top offset (relative to screen) position of the list var prevY = parseInt(list.offsetTop); //This has the original Top CSS position of the list var cssY = list.style.top; cssY = parseInt(cssY.substring(0, cssY.length - 2)); //Add the start of the touching list.addEventListener("touchstart", function (e) { //touch started ? YES isTouched = true; //initialize the touched point prevY = e.changedTouches[0].clientY; //we use css3 transitions when available for smooth sliding list.style.transition = ""; e.preventDefault(); }, false); list.addEventListener("touchend", function (e) { //on touchup we cancel the touch event isTouched = false; //now if the list has moved downwards, it should come up but in a transition list.style.transition = "top 1s"; if (isMoved) { //show the loader div loader.style.display = "block"; loadNewData(); } list.style.top = cssY + 'px'; isMoved = false; e.preventDefault(); }, false); list.addEventListener("touchmove", function (e) { if (isTouched) { if (e.changedTouches[0].clientY > prevY) { //on touchmove, we add the exact amount fingers moved to the top of the list var change = e.changedTouches[0].clientY - prevY; //and add it to the style list.style.top = cssY + change + 'px'; isMoved = true; } } e.preventDefault(); }, false); //binding mouse events to make this work in desktop browsers as well list.addEventListener("mousedown", function (e) { isTouched = true; prevY = e.clientY; list.style.transition = ""; e.preventDefault(); }, false); list.addEventListener("mouseup", function (e) { isTouched = false; list.style.transition = "top 1s"; if (isMoved) { loader.style.display = "block"; loadNewData(); } list.style.top = cssY + 'px'; isMoved = false; e.preventDefault(); }, false); list.addEventListener("mousemove", function (e) { if (isTouched) { if (e.clientY > prevY) { var change = e.clientY - prevY; list.style.top = cssY + change + 'px'; isMoved = true; } } e.preventDefault(); }, false); function loadNewData() { setTimeout(function () { list.innerHTML = '<li>new user</li><li>new user 2</li>' + list.innerHTML; loader.style.display = "none"; }, 1000); /** * do what ever to get data here */ }
<body> <h1>new pull to refresh list</h1> <div class="list"> <div id="touchloader" style="text-align: center;display: none;">Loading.....</div> <ul id="touchlist" style="position: relative;top:0px;"> <li>manzzup</li> <li>test</li> <li>manujith</li> <li>other</li> <li>this</li> </ul> </div> <script> </script> </body>
.list li { list-style-type:none; line-height:50px; height:50px; font-size:1.5em; border-bottom:1px solid #6BA5E7; }