hcker2000
hcker2000

Reputation: 615

jQuery Mobile Switch to "page" thats already in dom with .changePage()

Right now my DOM has three divs with data-roll="page", all of them have unique id's. If I use the following code it works but jQuery Mobile is creating a new node rather than switching to the already existing node.

$('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) {
        console.log(nextpage);
        $.mobile.changePage(nextpage.attr('id'), {transition: 'slide'});
    }
});

I have also tried passing just nextpage to the .chagePage method but when ever the pages have an id set I get the following error.

TypeError: b.split is not a function

So I'm looking to switch directly to the already existing "page" thats in the DOM rather than create a new one from my swipeleft handler.

I'm using jQuery 1.7.1 and jQuery Mobile 1.1.1

Upvotes: 2

Views: 2337

Answers (1)

Jasper
Jasper

Reputation: 76003

Have you tried passing-in a jQuery object rather than a string?

$(document).delegate('.ui-page', "swipeleft", function(){
    var $nextPage = $(this).next('[data-role="page"]');
    // swipe using id of next page if exists
    if ($nextPage.length > 0) {
        $.mobile.changePage($nextPage, { transition: 'slide' });
    }
}).delegate('.ui-page', "swiperight", function(){
    var $prevPage = $(this).prev('[data-role="page"]');
    // swipe using id of next page if exists
    if ($prevPage .length > 0) {
        $.mobile.changePage($prevPage, { transition: 'slide', reverse : true });
    }
});​

Here is a demo: http://jsfiddle.net/V3CXF/

Otherwise I think you have to prepend a hash mark to your string ID to make it a valid selector:

$(document).delegate('.ui-page', "swipeleft", function(){
    var $nextPage = $(this).next('[data-role="page"]');
    // swipe using id of next page if exists
    if ($nextPage.length > 0) {
        $.mobile.changePage('#' + $nextPage[0].id, { transition: 'slide' });
    }
}).delegate('.ui-page', "swiperight", function(){
    var $prevPage = $(this).prev('[data-role="page"]');
    // swipe using id of next page if exists
    if ($prevPage .length > 0) {
        $.mobile.changePage('#' + $prevPage[0].id, { transition: 'slide', reverse : true });
    }
});​

Here is a demo: http://jsfiddle.net/V3CXF/1/

Notice I swapped .live() out for .delegate() as .live is now depreciated (as of jQuery Core 1.7). If you are using jQuery Core 1.7 or newer, you can use .on() instead.

Docs for .live(): http://api.jquery.com/live

Upvotes: 2

Related Questions