0

I've been pulling my hair out for hours and I know I'm missing something, somewhere...I've found a solution that solves 80% of what I need to achieve... Best way to make twitter bootstrap tabs persistent by dootzuky

$(document).ready(function() {
    // show active tab on reload
    if (location.hash !== '') $('a[href="' + location.href + '"]').tab('show');

    // remember the hash in the URL without jumping
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
       if(history.pushState) {
            history.pushState(null, null, '#'+$(e.target).attr('href').substr(0));
       } else {
            location.hash = '#'+$(e.target).attr('href').substr(0);
       }
    });
});

But substr(0) isn't 1 as per code in OP SE link

After I implement this snippet, I see two problems (one is minor and I can probably find an answer later)

  1. I seem to get a double URL when clicking a tab...

    The page with the tabs present is like this

    www.devsite.dev:8888/some_page.html?id=25&dis=4

    But when I click a tab I want the "dis=4" to update as what is in the href="some_page.html?id=25&dis=5#History_of_Posts"

    Instead, I get this:

    www.devsite.dev:8888/some_page.html?id=25&dis=4#some_page.html?id=25&dis=5#History_of_Posts

    Rather than what I'd like (or expected)

    www.devsite.dev:8888/some_page.html?id=25&dis=5#History_of_Posts

  2. Also, the history(back button) seems to show multiple entries for this url even though it's only been clicked once?

Any help or advice would be greatly appreciated - thank you in advance.

Community
  • 1
  • 1

1 Answers1

0

This accepted answer https://stackoverflow.com/a/9393768/4494581 actually pointed me in the right direction to resolving my issue...

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
} 

    // Change hash for page-reload
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;

})

The only trouble was the page jumping, so after reading some of the other answers I implemented Gavin's answer that incorporates history.pushState which does all what I needed it to do. https://stackoverflow.com/a/32615601 incase this helps anyone else in the future.

Community
  • 1
  • 1