2

I'm a javascript noob and I'm wondering how do I implement the answer to this question?

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I want to use this code on the same page that the tabs are located....

  <script type="text/javascript">
    // 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', function (e) {
      window.location.hash = e.target.hash;
    })
  </script>

Where inside the page containing the tabs should I plugg this in.

Again, so sorry for being such a noob.

Community
  • 1
  • 1
Jessi
  • 791
  • 1
  • 12
  • 24
  • If you want to simply show a tab form a link on the __same__ page, you don't need to use the approach do this, instead use the script see [this other answer of mine](http://stackoverflow.com/questions/15360112/jump-to-specific-tab-from-another-tab-with-bootstraps-nav-tabs/15365279#15365279), with a working jsFiddle example. – Marijn Mar 13 '13 at 07:39

2 Answers2

4

Bootstrap 3 solution:

<script type="text/javascript">
$(function() {
  // 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
  $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    window.location.hash = e.target.hash;
  });
});
</script>
coderberry
  • 3,040
  • 3
  • 26
  • 28
  • Awesome! one question: when i paste in the url with "#" the page goes to where the #starts. How would I be able to just have the page go to the top? I can see how going to # would be useful for sections in wikipedia pages, but we are just using 3 horizontal tabs to just display different content – kibaekr Feb 28 '14 at 11:38
  • I'm stupid. I just realized that I misunderstood the question. I was looking for a solution that simply changes the url when you click on the tabs – kibaekr Feb 28 '14 at 11:42
  • Uncaught Error: Syntax error, unrecognized expression: .nav-tabs a[href=#/mytab] – Andrea Borgogelli Avveduti Sep 09 '15 at 11:11
1

Try wrapping the code in the $(document).ready() function

$(document).ready(function() {
 //your code here...
});

What you have above won't work as the DOM won't be ready when it runs. Using the $(document).ready() function will delay execution until the dom has loaded. It can go pretty much anywhere in the page containing the tabs. Some people think it should go within the head section, some think it should go at the end. But read here for more in-depth answers on that: Where do I put the $(document).ready()?

See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Community
  • 1
  • 1
Simon C
  • 9,458
  • 3
  • 36
  • 55