jQuery addClass example
Change class name on click in jQuery
HTML
<div>
Logo
</div>
<nav class="nav">Nav Sample</nav>
<div class="content"></div>
<div id="debug-text"></div>
<div id="social-float">
<div class="sf-twitter">twitter</div>
<div class="sf-facebook">facebook</div>
</div>
<div id="footer">footer sample</div>
CSS
body {
padding: 0;
margin: 0;
}
.nav, #footer {
height: 600px;
background-color: #aaa;
}
.content {
height: 600px;
background: #eee;
}
#debug-text {
position: fixed;
top: 0;
margin: 0 auto;
display: block;
width: 250px;
text-align: center;
background: #ffeecc;
margin-left: -125px;
left: 50%;
}
#social-float {
position: fixed;
right: 0;
padding: 5px;
background-color: #333;
color: #fff;
}
JavaScript
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');
}
// code for debugging : Start
var fEt = $fixedElem.css('top');
var fEb = $fixedElem.css('bottom');
$('#debug-text').html(`
currentScrollOffset: ${currentScrollOffset}<br />
navbar effective height: ${navbarEffectiveHeight}<br />
footer offset: ${footerOffset}<br />
fixed elem:<br />top = ${fEt}; bottom: ${fEb};
`);
// code for debugging : End
}
$(document).ready(checkOffset);
$(document).scroll(checkOffset);