Update menu in jQuery Mobile based on swipe event

I have a menu that updates based on a click event, which is pretty simple because I can overlay the click on the actual button, but how can I get the menu to respond to page changes through scrolling?

Here's my working JSFiddle that allows clicks and scrolls: http://jsfiddle.net/QFX5x/1/

I started using pagebeforeshow and .mobile.path.parseURL for the hash tag, but it is incompatible.

        $(document).live("pagebeforeshow", function() {
            var obj = $.mobile.path.parseUrl(window.location.href);
            var newPage = '.' + obj.hash;

            alert(newPage);

            //$(newPage).addClass("active");
            //$(newPage).siblings().removeClass("active");
        });

      

+1


source to share


1 answer


When I want to mimic some type of event, I just use .trigger()

to fire that event on the correct element, rather than re-writing my code to trigger the event handler in two different situations. Since your code works with an event click

, you can fire the event click

on the correct link based on the current list item active

:

$(function(){

    //cache all of the list-items in the navigation div
    var $nav   = $('#nav').children().children(),

        //also cache the number of list-items found
        totNav = $nav.length;

    //notice the use of `.on()` rather than `.live()` since the latter is depreciated
    $(document).on('swipeleft', '.ui-page', function() {

        //get the next index based on the current list-item with the `active` class
        var next = ($nav.filter('.active').index() + 1);

        //if you're already on the last page then stop the function and do nothing
        if (next === totNav) {
            return;
            //you could use this next line to wrap to the beginning rather than not doing anything
            //next = 0;
        }

        //trigger a `click` event on the link within the list-item at the next index
        $nav.eq(next).children().trigger('click');

    //notice I'm chaining the `.on()` function calls on the `$(document)` selection
    }).on('swiperight', '.ui-page', function() {

        //get the previous index
        var prev = ($nav.filter('.active').index() - 1);

        if (prev === -1) {
            return;
            //you could use this next line to wrap to the beginning rather than not doing anything
            //prev = (totNav - 1);
        }
        $nav.eq(prev).children().trigger('click');
    }).on('click', '#nav a', function(e) {

        //more chaining
        $(this).parent().addClass("active").siblings().removeClass("active");
    });
});​

      



Here's a demo: http://jsfiddle.net/QFX5x/4/

+1


source







All Articles