viperfx viperfx - 5 months ago 10x
Javascript Question

Page jumps down when tab is clicked once active

So on the site STVPlus we use bootstrap and the tabs script to show episodes and articles lists for various tv shows. I am having an issue where once the page has loaded (usually) it works fine, you can select a tab and the appropriate div will show. However if you select an already active div the page jumps down.Also when loading the page with a hash tag like so episodes hash tag link, then it automatically jumps down when page is fully loaded. I have tried stepping through the JS code using chrome dev tools, however I could not find anything obvious.

Any help would be appreciated.

Sample code:


// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;

if ( hash == '#episodes'){
$('.nav-pills a:last').tab('show');
$('.nav-pills a:first').tab('show');


// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
return false;

the episodes div container is like so

<div class="tab-pane" id="episodes"> ..... </div>

and the tab you click is like so

<ul class="nav nav-pills pull-right" data-tabs="tabs">
<li class="active"><a href="<?php echo current_url(); ?>#articles">Latest Articles</a></li>
<li><a href="<?php echo current_url(); ?>#episodes">Upcoming Episodes</a></li>

I use the latest jquery, with


This is what would be my approach concerning your problem :

I'm not sure that you need the hashchange plugin - except for some document.location.hash fallback (if there's any).

The following code uses the classic bootstrap tabs, manually activated, and a bit of onready code that will show the tab matching the hash.

var hasHash = false;
var hash = document.location.hash;
if(hash) {
    hasHash = true;
    var $toggleTab = $('a[href='+hash+']');
    if($toggleTab.length) $'show');

Tab activation :

$('.nav > li > a').click(function(event) {
    var $this = $(this);
    if(hasHash) document.location.hash = $this.attr('href');

Based on the HTML :

<ul class="nav nav-pills" data-tabs="tabs">
    <li class="active"><a href="#articles" data-target="#articles-tab">Latest Articles</a></li>
    <li><a href="#episodes" data-target="#episodes-tab">Upcoming Episodes</a></li>
<div class="tab-content">
    <div class="tab-pane" id="episodes-tab">episodes</div>
    <div class="tab-pane active" id="articles-tab">articles</div>

Demo (jsfiddle) and Hash demo (jsfiddle)