Reputation: 59
I have a fixed div on the right side of my page. I have it set up to scroll with the page and not overlap the footer and it works great. The problem is that it overlaps the nav when scrolling up. Is there any way to have it work for both? I tried to create a new function
function checkOffset() {
var a = $(document).scrollTop() + window.innerHeight;
var b = $('#footer').offset().top;
if (a < b) {
$('#social-float').css('bottom', '10px');
} else {
$('#social-float').css('bottom', (10 + (a - b)) + 'px');
}
}
$(document).ready(checkOffset);
$(document).scroll(checkOffset);
<nav class="nav">Nav Sample</nav>
<div id="social-float">
<div class="sf-twitter">twitter</div>
<div class="sf-facebook">facebook</div>
</div>
<div id="footer">footer sample</div>
Upvotes: 2
Views: 305
Reputation: 442
Here checkout this fiddle for the solution. I have added debug text on the page and also considered the fact that nav-bar might be offset due to other divs at the top.
/**
* This function checks for both top and bottom edges to position itself
* on the page
*/
function checkOffset() {
var documentTop = $(document).scrollTop();
var currentScrollOffset = documentTop + window.innerHeight;
var footerOffset = $('#footer').offset().top;
var navbarEffectiveHeight = $('.nav').outerHeight() + $('.nav').offset().top;
var $fixedElem = $('#social-float');
var fixedElemHeight = $fixedElem.outerHeight();
// until page scroll crosses navbar bottom edge (offset)
if (currentScrollOffset < navbarEffectiveHeight) {
$fixedElem.css('top', (currentScrollOffset + 10) + 'px');
$fixedElem.css('bottom', 'unset');
// page scroll crossed navbar bottom edge but not to extend of the height of fixed div
// including the top and bottom spacing for it which is 20px
} else if (currentScrollOffset < navbarEffectiveHeight + fixedElemHeight + 20) {
$fixedElem.css('top', (window.innerHeight - (currentScrollOffset - navbarEffectiveHeight) + 10) + 'px');
$fixedElem.css('bottom', 'unset');
// page scroll hasn't crossed footer top edge (offset)
} else if (currentScrollOffset < footerOffset) {
$fixedElem.css('bottom', '10px');
$fixedElem.css('top', 'unset');
// page scroll crossed footer top edge (offset)
} else {
$fixedElem.css('bottom', (10 + (currentScrollOffset - footerOffset)) + 'px');
$fixedElem.css('top', 'unset');
}
}
$(document).ready(checkOffset);
$(document).scroll(checkOffset);
Upvotes: 1