0

I am using the Bootstrap framework through out the entire site for the responsive design ability. I am also using AJAX calls to switch between every page. On one page I am using the Bootstrap tabs to switch between page contents. Everything works perfectly when you are directed to the page through any of the ajax links but if you manually type in the url the tab contents wont change. The tabs themselves will change when you click on them but the content stays on the original content. I originally though it might have something to do with the javascript I'm using so that you can direct the user to a certain tab with a hashtag but it still doesn't work when I remove the code. Here is the code:

 <div class="tabbable"> <!-- Only required for left/right tabs -->
     <ul class="nav nav-tabs">
         <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
         <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
         <li><a href="#tab3" data-toggle="tab">Tab 3</a></li>
         <li><a href="#tab4" data-toggle="tab">Tab 4</a></li>
     </ul>
 <div class="tab-content">
     <div class="tab-pane active" id="tab1">
         Tab #1
     </div>
     <div class="tab-pane" id="tab2">
         Tab #2
     </div>
     <div class="tab-pane" id="tab3">
         Tab #3
     </div>
     <div class="tab-pane" id="tab4">
         Tab #4
     </div>
</div>
<script>
    $(function(){
        if (window.location.hash) {
            var hash = window.location.hash;
            var tab = $('[data-toggle="tab"][href="' + hash + '"]');

            tab.show();
            tab.tab('show');
        }
    });
</script>

Can anyone help me with this?

madth3
  • 7,275
  • 12
  • 50
  • 74

1 Answers1

0

You have to add a listener to the hashchange window event.

You probably opened the page without a hash. At this point, your script was executed. When you change the hash in your adress bar, the page will not be reloaded. So there is no-one to handle that event. For this you have the hashchange event to react to such changes.

See the MDN documentation for more info and examples on this event.

If you are using jQuery, check out this answer.

Community
  • 1
  • 1
Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168