Reputation: 1946
I have a menu that is updating based on a click event, which is pretty easy because I can base the click on the actual button, but how do I make the menu react to page changes via swiping?
Here's my working JSFiddle that allows for clicks and swipes: http://jsfiddle.net/QFX5x/1/
I started to use pagebeforeshow and .mobile.path.parseURL for the hash tag, but it isn't consistent.
$(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");
});
Upvotes: 1
Views: 806
Reputation: 76003
When I want to mimic some type of event I just use .trigger()
to trigger that event on the correct element rather than re-writing my code to run the event handler in two different situations. Since your code works with the click
event, you can trigger a click
event on the correct link based on the current active
list-item:
$(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 is a demo: http://jsfiddle.net/QFX5x/4/
Upvotes: 1