We all know the very nice pull to refresh functionality that was introduced in the Twitter app for iOS. Though patented by Twitter, it has been implemented in many apps since. I was working on a PhoneGap app with a page containing a list of news items and was wondering how difficult it would be to implement the pull to refresh functionality on that page. This blog describes how to make your PhoneGap pull to refresh implementation.
PhoneGap pull to refresh
Google led me to the iScrollView JQuery Mobile plugin to use the iScroll scroller. Using this plugin it was fairly easy to implement pull to refresh. A few steps had to be taken. First, include the plugin stylesheets and javascript files in your html file.
<link rel="stylesheet" href="css/jquery.mobile.iscrollview.css" type="text/css"/> <link rel="stylesheet" href="css/jquery.mobile.iscrollview-pull.css" type="text/css"/> <script src="js/lib/iscroll.js"></script> <script src="js/lib/jquery.mobile.iscrollview.js"></script>
Next, add the attribute data-iscroll to the container you want to add the functionality to. In my case, this was the content container of the page. See the first line in the code snippet below.
<div id="scroller" data-role="content" data-iscroll=""> <div class="iscroll-pulldown"> <span class="iscroll-pull-icon"></span> <span class="iscroll-pull-label" data-iscroll-loading-text="News is being refreshed" data-iscroll-pulled-text="Release to refresh the news"> Refresh the news </span> </div> <div id="newsList"></div> </div>
The <div> with class iscroll-pulldown contains the definition of the pulldown content that will be displayed when the user pulls down the container. Different data tags are available for the different states the pull down dialog can be in. data-iscroll-loading-text for the text to be displayed when the update action is executed and data-iscroll-pulled-text for the text to be displayed when the user has pulled down the container.
So, how do we implement the code to actually update the news items? We need some Javascript for that ofcourse! On the pageinit event of the page we need to bind javascript functions to the different events that have been defined by the plugin. See the code below how the javascript function onPullDown is defined for the iscroll-onpulldown event.
$('#newsPage').live("pageinit", function(event) { $(".iscroll-wrapper").bind( { iscroll_onpulldown : onPullDown }); }); function onPullDown(event, data) { //do your stuff here... }
This is all that is needed to implement the pull to refresh functionality in your JQuery Mobile PhoneGap application. Enjoy!