Skip to content

Instantly share code, notes, and snippets.

@mikeabbott10
Forked from josheinstein/gist:5586469
Last active October 15, 2022 02:08
Show Gist options
  • Save mikeabbott10/ca7ab052f21eaf0f5c9c8c3f3552dd3a to your computer and use it in GitHub Desktop.
Save mikeabbott10/ca7ab052f21eaf0f5c9c8c3f3552dd3a to your computer and use it in GitHub Desktop.
Clean back button handling with Twitter Bootstrap tabs. This now puts together the power of the 2 main works speaking of bootstrap tabs navigation (links in code).
/*---------------------
Clean back button handling with Twitter Bootstrap tabs.
This now puts together the power of the 2 main works speaking of bootstrap tabs navigation.
* useful links:
*(i) https://gist.github.com/josheinstein/5586469 ( http://web.archive.org/web/20221015013803/https://gist.github.com/josheinstein/5586469 )
*(ii) http://www.redotheweb.com/2012/05/17/enable-back-button-handling-with-twitter-bootstrap-tabs-plugin.html ( http://web.archive.org/web/20211202214354/http://www.redotheweb.com/2012/05/17/enable-back-button-handling-with-twitter-bootstrap-tabs-plugin.html )
----------------------*/
jQuery(function ($) {
$(function () {
// we always want hash to start with "#!"
if(location.hash.slice(0,2) != "#!"){
location.replace('#!home-content');
}else{
// good hash already. Go to the right tab
$("a[href='#" + location.hash.slice(2) + "']").tab("show"); // link (i)
}
// add a hash to the URL when the user clicks on a tab
$('a[data-toggle="pill"]').on('click', function(e) { // switch to a[data-toggle="tab"] if needed
var hash = $(e.target).attr("href");
if (hash.slice(0,1) == "#") {
history.pushState(null, null, "#!" + hash.slice(1)); // link (ii)
}
});
// navigate to a tab when the history changes
// link (ii)
window.addEventListener("popstate", function(e) {
if (location.hash.slice(0,2) == "#!") {
$("a[href='#" + location.hash.slice(2) + "']").tab("show");
} else {
$('.nav-item a:first').tab('show'); // (home is the first one for me)
location.replace('#!home-content');
}
});
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment