Alright, I\'m having trouble understanding the Bootstrap Affix component. My goal is to have a \"Back to Top\" link appear at the bottom left of the screen (in the margin) if/wh
thanks for the back to top button, proved useful for me as well :)
one minor improvement though would be to avoid using the onclick=""
on the <a>
tag but instead using jQuery's
event registrator:
HTML:
...
<a href="#top" id ="backToTopBtn" class="well well-sm">
...
JS:
$('#backToTopBtn').click(function(){
$('html,body').animate({scrollTop:0},'slow');return false;
});
Now that I understand the Affix component better, I have come up with the solution. After specifying a top offset and adjusting the CSS, it's working nicely. The link will scroll into view and then "pin" to the bottom. For pages which do not have a scroll bar, the link is never enabled. I've updated the JS Fiddle (here) with a working example. Key pieces are:
HTML:
<!-- child of the body tag -->
<span id="top-link-block" class="hidden">
<a href="#top" class="well well-sm" onclick="$('html,body').animate({scrollTop:0},'slow');return false;">
<i class="glyphicon glyphicon-chevron-up"></i> Back to Top
</a>
</span><!-- /top-link-block -->
JS:
<script>
// Only enable if the document has a long scroll bar
// Note the window height + offset
if ( ($(window).height() + 100) < $(document).height() ) {
$('#top-link-block').removeClass('hidden').affix({
// how far to scroll down before link "slides" into view
offset: {top:100}
});
}
</script>
CSS:
<style>
#top-link-block.affix-top {
position: absolute; /* allows it to "slide" up into view */
bottom: -82px;
left: 10px;
}
#top-link-block.affix {
position: fixed; /* keeps it on the bottom once in view */
bottom: 18px;
left: 10px;
}
</style>
Note: I was not able to use the affix bottom offset (example) to hide the link for short pages due to a bug with affix container height calculation (Bootstrap Issue # 4647). I'm sure there is a workaround and would welcome the solution to this method.