Reputation: 4008
I have a couple of tabs with varying heights. How do I prevent the page from jumping to the top of the container when I click on a tab link?
JSFiddle
http://jsfiddle.net/q1tdsar1/1/ Steps to reproduce issue: Click on tab 3, scroll down as if reading the content of tab 3 then click tab 1. Boom > Page Jump!
Here's my JS:
$('#tabs div.tab').hide();
$('#tabs div.tab:first').show();
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div.tab').hide();
$(currentTab).show();
return false;
});
Here's the HTML
<div id="tabs">
<ul class="nav">
<li><a href="#tab-1">Tab 1</a></li>
<li><a href="#tab-2">Tab 2</a></li>
<li><a href="#tab-3">Tab 3</a></li>
</ul>
<div id="tab-1" class="tab">Some content</div>
<div id="tab-2" class="tab">Some longer content</div>
<div id="tab-3" class="tab">Some even longer content</div>
</div>
Here's CSS:
#tabs ul.nav {
float: left;
width: 500px;
}
#tabs li {
margin-left: 8px;
list-style: none;
}
* html #tabs li {
display: inline;
}
#tabs li,
#tabs li a {
float: left;
}
#tabs ul li.active {
border-top:2px #FFFF66 solid;
background: #FFFFCC;
}
#tabs ul li.active a {
color: #333333;
}
#tabs div.tab {
background: #FFFFCC;
clear: both;
padding: 15px;
}
#tabs ul li a {
text-decoration: none;
padding: 8px;
color: #000;
font-weight: bold;
}
Upvotes: 0
Views: 2750
Reputation: 167240
You may need to use an equal height for all the tabs you have so far. So a script might be helpful, as this is not the page jump that happens, as you already have return false
in the place of event.preventDefault();
.
TabDivHeight = 0;
$('#tabs div.tab').each(function () {
$(this).show();
if ($(this).height() > TabDivHeight)
TabDivHeight = $(this).height();
$(this).hide();
});
$('#tabs div.tab').height(TabDivHeight);
Fiddle: http://jsfiddle.net/342fsu8o/
Or if you would prefer a CSS version, I would say, go for this:
#tabs div.tab {
background: #FFFFCC;
clear: both;
padding: 15px;
max-height: 200px;
overflow: auto;
}
Fiddle: http://jsfiddle.net/jv3bmtof/
Or if you prefer a smooth transition, you may use slideUp()
and slideDown()
:
$('#tabs ul li a').click(function () {
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div.tab').slideUp();
$(currentTab).slideDown();
return false;
});
Fiddle: http://jsfiddle.net/tdxyLvLs/
Upvotes: 1