Swipe to go back in jQuery Mobile?

Anders picture Anders · Aug 22, 2011 · Viewed 18.7k times · Source

I'm trying out jQuery Mobile, because I wasn't able to get swipe to go back a page to work well in jQTouch. But being new to jQuery Mobile, I have no idea how to go about implementing swipe, and how to make a swipe right cause a return to the previous page. I've been Googling and searching the docs, but can't find it, so I would really appreciate some help.

EDIT:

I found this solution when Googling a bit more:

        $('body').live('pagecreate', function (event) {
            $('div.ui-page').live("swipeleft", function () {
                var nextpage = $(this).next('div[data-role="page"]');
                // swipe using id of next page if exists
                if (nextpage.length > 0) {
                    $.mobile.changePage(nextpage, 'slide');
                }
            });
            $('div.ui-page').live("swiperight", function () {
                var prevpage = $(this).prev('div[data-role="page"]');
                // swipe using id of previous page if exists
                if (prevpage.length > 0) {
                    $.mobile.changePage(prevpage, 'slide', true);
                }
//                history.back();
//                return false;
            });
        });

This does work, but doesn't seem very stable. It jumps a bit back and forth when you swipe. I also tried the commented out code at the end - history.back(), which was suggested on another site. But that seemed even more unstable, causing all kinds of weird jumps.

Answer

Timothy Perez picture Timothy Perez · Aug 22, 2011

You can use the jQuery .live "swipe left" and "swipe right" events.

Example:

 $(document).ready(function() {

      $('.yourPage').live('swipeleft swiperight',function(event){
          if (event.type == "swiperight") {
              var prev = $("#previndex",$.mobile.activePage);
              var previndex = $(prev).data("index");
              if(previndex != '') {
                  $.mobile.changePage({url:"index.php",type:"get",data:"index="+previndex},"slide",true);
              }
          }
          if (event.type == "swipeleft") {
              var next = $("#nextindex",$.mobile.activePage);
              var nextindex = $(next).data("index");
              if(nextindex != '') {
                  $.mobile.changePage({url:"index.php",type:"get",data:"index="+nextindex});
              }
          }
          event.preventDefault();
      });
});

Also, this YouTube video might help you as well. http://www.youtube.com/watch?v=Ij1RYI1p7rM