Twitter Bootstrap Tabs: How to jump to anchor?

javascript, twitter-bootstrap

Solution

The Tab Data API uses `preventDefault()`, which is why the browser doesn't scroll to the panes. (See source code.)

The simplest thing to do would probably be to disable the event listener defined in Tab code, and then make your own without the call to `preventDefault()`.

Something like:

// disable old listener
$('body').off('click.tab.data-api')

// attach new listener
$('body').on('click.scrolling-tabs', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
  //e.preventDefault()
  $(this).tab('show')
})

If you only wanted certain tabs to trigger a browser scroll, you could add some conditional statements in here to control whether or not `preventDefault()` is called.

Finally, make sure these overrides run after the tab plugin has been loaded.

Viewport Conditional

If you want to check the viewport and decide whether to scroll based on its width, you could try:

$('body').on('click.scrolling-tabs', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
  $(window).width() > 767 && e.preventDefault()
  $(this).tab('show')
})

In Bootstrap, 767 px is considered the upper limit of a "phone" viewport, but you can use whatever value you'd like.

Problem

I would like the page to jump to the "tabreveal" ID when a View details button is clicked. What JS would I need to make this happen? Code is as follows: ``` <div class="row"> <div class="span3 box1"> <h2>Web</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#web" data-toggle="tab">View details &raquo;</a></p> </div> <div class="span3 box2"> <h2>Video</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn" href="#video" data-toggle="tab">View details &raquo;</a></p> </div> <div class="span3 box3"> <h2>Print</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn" href="#print" data-toggle="tab">View details &raquo;</a></p> </div> </div> <div class="tab-content" id="tabreveal"> <div class="tab-pane" id="web">2</div> <div class="tab-pane" id="video">3</div> <div class="tab-pane" id="print">4</div> </div> ``` Thanks in advance for any replies!

Original source