millermedeiros / crossroads.js

JavaScript Routes
http://millermedeiros.github.com/crossroads.js/
1.44k stars 156 forks source link

using crossroads and hasher with jquery tabs navigation in spa #131

Closed kumarngrjn closed 9 years ago

kumarngrjn commented 9 years ago

Hey, This is more of a question than an issue.I currently have a spa where one of the pages contain jquery tabs. I use hasher and crossroads to route within my spa for different pages. I have currently set prependhash to empty string so that url looks like a.com#main . I think this is where the problem arises . In the page where i have jquery tabs if i click on one of the tabs , hasher thinks i need to navigate to a page and adds the tabs as a url like a.com#first_tab. Is there a way i can let the router know i am navigating a tab and don't want to navigate to a different page.

Thanks. Kumar.

My javascript crossroads.addRoute('mainpage'); crossroad.addRoute('secondpage'); crossroads.addRoute('thirdpage');

function handleHashChanges(newPage, oldPage) { $("#"+newPage).removeClass("inactive-page"); $("#"+oldPage).addClass('inactive-page'); }

hasher.changed.add(handleHashChanges); hasher.initialized.add(handleHashChanges); hasher.init(); hasher.prependHash = ''; hasher.setHash('mainpage');

JonathanWolfe commented 9 years ago

You'll have to attach a listener to the tab click events and call preventDefault and then set a listener for every a tag's click event and check to see if preventDefault has already been called.

Something like the below is how I do it.

Tab's click handler:

$('.tab-header').on('click', function(e) {

    e.preventDefault();
    // ... Activate tab switch

});

All <a> tag click handler:

$(document).on('click', 'a', function(e) {

    if ( e.defaultPrevented || e.isDefaultPrevented() ) {
        return false; // If another click handler is present, bail out
    }

    e.preventDefault();
    hasher.setHash($(this).attr('href'));
    return true;

});
sumitkm commented 9 years ago

Hi Kumar,

I prefer declaring a route called a.com/main/{tabName} and point it to the same page so that cross roads still does the routing but your page gets the additional parameter to tell it which tab it should show. This has the added advantage of automatic browser back button support. (sorry if the route is a little different that what you get with hasher. I use HistoryJS

Personally I think anything with an achor tag should navigate like on the web (and not do stuff like button click on desktop), but that's just me :-).

Cheers, Sumit.

Edit: The mail didn't show your script bits, sorry, so that route declaration would be (assuming the tabs are in the mainpage).

crossroads.addRoute('mainpage/{tabName}');
crossroad.addRoute('secondpage');
crossroads.addRoute('thirdpage');

Hope this helps.