UPDATE
I've updated the answer here so it can really works!
HTML
We need some basic html rules to work with the jQuery
- Navigation tabs (using list or table, doesn't matter)
- Some sections (marked with an ID)
- Anchors in the tabs that refers to section IDs
example:
<!DOCTYPE html>
<html>
<body id="#top">
<nav>
<ul>
<li><a href="#top">Home</a></li>
<li><a href="#web">Web</a></li>
<li><a href="#design">Design</a></li>
<li><a href="#photo">Photo</a></li>
</ul>
</nav>
<header><h2>HEADER</h2></header>
<section id="web"><h2>WEB</h2></section>
<section id="design"><h2>DESIGN</h2></section>
<section id="photo"><h2>PHOTO</h2></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
jQuery
That jQuery script will perfectly work with relative section heights. For that, we need:
- A function that calculates all section's top and bottom
- A function that verify if the scrolling position is between them
- Adding the
.current
class to the current section's tab
- Binding events so we recalculate scrolling position when scrolled and section heights when window is resized
example:
var currentTab = (function () {
//variables
var $window = $(window),
$section = $('section'),
$scrollPosition = $window.scrollTop(),
$sectionHeights = [];
//will calculate each section heights and store them in sectionHeights[] array
function resizeSectionHeights() {
$section.each(function (i) {
$sectionHeights[i] = $(this).outerHeight();
});
}
/*will calculate current scroll position. If it's between the top and bottom of a section,
the tab containing an href value of that section id will have the .current class.*/
function applyCurrentState() {
$scrollPosition = $window.scrollTop();
$section.each(function (i) { //we indent i at each section count, so we can find it's height in sectionHeight[]
var $anchor = $("nav a[href=#" + $(this).attr('id') + "]"),
$sectionTop = $(this).offset().top - 1, // -1 get rid of calculation errors
$sectionBottom = $sectionTop + $sectionHeights[i] - 1; // -1 get rid of calculation errors
if ($scrollPosition >= $sectionTop && $scrollPosition < $sectionBottom) {
$anchor.addClass('current');
} else {
$anchor.removeClass('current');
}
});
}
//binding events
$window.resize(resizeSectionHeights);
$window.scroll(applyCurrentState);
//initialization
resizeSectionHeights();
}());
CSS
For the css, just change the nav a.current
style so we notice that we are at this specific section.
FINAL
To see the final product, please check THIS JSFIDDLE.