Doc Table of Contents
Code to dynamically position a fixed element within the visible window area
by mrtsherman
HTML
<div id="projector_sidebar">
Table of Contents
</div>
<div id="body">
Some content
</div>
CSS
#projector_sidebar {
position: fixed;
top: 85px;
right: 25px;
height: 300px;
width: 200px;
border: 1px dashed gray;
}
#body {
height: 2000px;
}
JavaScript
var $toc = jQuery('#projector_sidebar');
//declare some global variables
var sidebarTop = $toc.offset().top;
var sidebarBot = $toc.height() + sidebarTop;
var bottomBuffer = 50;
//bind to scroll event of content window
jQuery(window).scroll(checkIt);
function checkIt() {
var scrollTop = jQuery(window).scrollTop();
var pageBottom = jQuery(window).height() + scrollTop - bottomBuffer;
if (sidebarBot < jQuery(window).height() && jQuery($toc).position().top == sidebarTop) {
return;
}
if (sidebarBot >= pageBottom) {
console.log('a')
$toc.css('bottom', 'auto');
$toc.css('top', sidebarTop - scrollTop);
} else {
console.log('b')
$toc.css('top', 'auto');
$toc.css('bottom', bottomBuffer);
}
}