13

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.

Anders
  • 12,556
  • 24
  • 104
  • 151

7 Answers7

6

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

Timothy Perez
  • 20,154
  • 8
  • 51
  • 39
  • Ok, thanks, but how do the prev and next variables work? How would I know the selectors (#previndex and #nextindex)? – Anders Aug 22 '11 at 06:47
  • Actually, please explain what is going on there in the first place, I have never declared a variable like that in jQuery, still not overly familiar with jQuery... – Anders Aug 22 '11 at 06:48
  • To answer your questions... next and prev are just variables that reference the div (#nextindex / #previndex) and the context. So it looks like this -> $('{element}',context); Similar to setting a variable to point to the element like this: var myDiv = $('#myDiv'); – Timothy Perez Sep 07 '11 at 18:15
  • You can also do var prev = $.mobile.activePage.find("#previndex"); Actually, this is probably a better/faster way then what I wrote above. – Timothy Perez Sep 07 '11 at 18:31
6

The answer from Timothy looks ok, but someone might prefer this similiar and ready solution:

http://filamentgroup.com/lab/jquery_mobile_pagination_plugin/

Published today by the home of 2 of the core jQuery Mobile Framework Team members

It's a plugin that lets the user easily swipe through pages. Might not fit every use-case, but sure is well-done (who else would know how to do something with jqm if not those guys? :) )

naugtur
  • 16,827
  • 5
  • 70
  • 113
  • Actually, it works fine with the buttons, but I see the same problems as with my original code that I included above - i.e. swiping is very unstable. It flickers back and forth and you never know what page you'll end up on after a swipe... – Anders Aug 30 '11 at 19:24
  • You might want to file that as a bug. Filament Group will sort it out for you ;) – naugtur Aug 31 '11 at 10:24
2

Correct solution is to use the history object and allow JQM to select the correct (left or right) transition based on which direction we send the browser.

Hence, set the default transition to "slide" and set all links with data-transition attribute to "fade", then attach history.back/forward to the swipe events:

$.mobile.defaultPageTransition = 'slide';
$( "body" ).on( 'swiperight', function() {history.back()}); 
$( "body" ).on( 'swipeleft', function() {history.forward()});   
$("a").attr("data-transition", "fade");

If you're creating dynamic content (and I damn well hope you are young man), be sure to set the data-transition="fade" attribute on all links after triggering the "create" event.

eg:

$("#mydiv")
.html("<a href="#page-somewhere"></a>")
.trigger("create")
.find("a").attr("data-transition", "fade");
1

Just sharing my code. I have been fiddling with this too, and I ended up having this:

var allowGlobalSwipe = true; // If you want to disable it at some point

$(function() {
  $(window).on("swipeleft", jqmForward).on("swiperight", jqmBack);

  // This is an example of where you may want to disable the swipe
  $('#slideContainer').swiper({
    onTouchStart: function () { allowGlobalSwipe = false; },
    onTouchEnd: function () { allowGlobalSwipe = true; }
  });
});

function jqmBack(e) {
  if (!allowGlobalSwipe) return;
  var prevpage = $('div.ui-page-active').prevAll('div[data-role="page"]');
  if (prevpage.length > 0)
    $.mobile.changePage($(prevpage[0]), { transition: "slide", reverse: true }, true, true);
}
function jqmForward(e) {
  if (!allowGlobalSwipe) return;
  var nextpage = $('div.ui-page-active').nextAll('div[data-role="page"]');
  if (nextpage.length > 0)
    $.mobile.changePage($(nextpage[0]), { transition: "slide" }, false, true);
}

Note that I use prevAll and nextAll because the previous page's div may not always be immediately before the current page's div.

Aximili
  • 28,626
  • 56
  • 157
  • 216
1

In jquery.mobile-1.0-rc2, swipe back is mentioned as

$.mobile.changePage('topage', { transition: "slide", reverse: true, });

Sudheer
  • 479
  • 1
  • 4
  • 9
0

In jquery.mobile-1.0-rc2, swipe to back to be mentioned as

$.mobile.changePage('topage', {  transition: "slide", 
                             reverse: true,
                           });
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
Sudheer
  • 9
  • 1
-2
function ChangePage(pageId,iPageIndex) {
    var forward = iCurrCardIndex < iPageIndex;
    iCurrCardIndex = iPageIndex;

    $.mobile.changePage("#" + pageId, "slide", !forward, true);
}
uzay95
  • 16,052
  • 31
  • 116
  • 182
  • 1
    I don't understand this answer. What is it doing? Is it some sort of override for mobile.ChangePage? And if so, how do I use it? Also, what is iCurrCardIndex etc? – Anders Aug 30 '11 at 19:25