Search code examples
jquery-mobile

jQuerymobile nativedroid2 Tabs swipe


<div data-role="header" data-position="fixed" class="wow fadeIn">
            <a href="#leftpanel" class="ui-btn ui-btn-left"><i class="zmdi zmdi-menu"></i></a>
            <h1 class="wow fadeIn" data-wow-delay='0.4s'>Tabs</h1>

            <ul data-role="nd2tabs" >
                <li data-tab="friends">Friends</li>
                <li data-tab="work" data-tab-active="true">Work</li>
                <li data-tab="holiday">Holiday</li>
                <li data-tab="colors">Colors</li>
            </ul>

        </div>

I have nativeDroid2b Tabs jquerymobile material design from natriveDroid2/Tabs.

How can I enable swipe feature in this tabs (ie switch between tabs content).

I wrote code for this, but it's not working:

$(function () {
            function changeNavTab(left) {
                var $tabs = $("div[data-role=nd2tabs] li ", $("div[data-role=nd2tabs].nd2Tabs-active"));
                var curidx = $tabs.closest("li.nd2Tabs-active").parent().index();
                console.log($tabs);
                var nextidx = 0;
                if (left) {
                    nextidx = (curidx == $tabs.length - 1) ? 0 : curidx + 1;
                } else {
                    nextidx = (curidx == 0) ? $tabs.length - 1 : curidx - 1;
                }
                $tabs.eq(nextidx).click();
            }

            $("div[role=main]").on("swipeleft", function (event) {

                changeNavTab(true);
            });

            $("div[role=main]").on("swiperight", function (event) {

                changeNavTab(false);
            });
        });

Kindly help me, thanks in advance.


Solution

  • First, use pagecreate instead of the regular jQuery document.ready:

    $(document).on("pagecreate", "#page1", function () {
        $("div[role=main]").on("swipeleft", function (event) {
            changeNavTab(true);
        });
    
        $("div[role=main]").on("swiperight", function (event) {
            changeNavTab(false);
        });
    });
    

    Next, in changeNavTab(), the selector should be ul[data-role="nd2tabs"] instead of div[data-role="nd2tabs"]:

    function changeNavTab(left) {
        var $tabs = $('ul[data-role="nd2tabs"] li');
        console.log($tabs);
        var len = $tabs.length;
        var curidx = 0;
        $tabs.each(function(idx){
            if ($(this).hasClass("nd2Tabs-active")){
                curidx = idx;
            }
        });
    
        var nextidx = 0;
        if (left) {
            nextidx = (curidx >= len - 1) ? 0 : curidx + 1;
        } else {
            nextidx = (curidx <= 0) ? len - 1 : curidx - 1;
        }
        $tabs.eq(nextidx).click();
    
    }
    

    DEMO