Back button and tabs in Bootstrap

If you are using the tabs component in Twitter Bootstrap and want to navigate to a specific tab when the browsers back button is pressed you can use the onhashchange event to detect when the button is pressed. The code example below is navigating back to first tab when back button is pressed.

In the example code for Bootstrap tabs they added preventDefault to the click event handler for the tabs. To get this solution to work you need to remove preventDefault from the event handler.

var currentHash = null;
            window.onhashchange = function () {
                if (currentHash === location.hash) {
                    $("#tabs a:first").tab('show');
                    window.onhashchange = null;
            currentHash = location.hash;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.