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/when the page is scrolled below the top of the content. My page has a NavBar fixed to the top and a container for the body. Below is the general idea of where I'm at but I've also setup a JS Fiddle that demonstrates my setup. I'm also not a pro at positioning so that is part of my issue too.
<div class="navbar navbar-fixed-top">...</div>
<div class="content-container" id="top">
<p>Content that is longer than the viewport..</p>
<span id="top-link" data-spy="affix">
<a href="#top" class="well well-sm">Back to Top</a>
</span>
</div>
<style>
.navbar-fixed-top + .content-container {
margin-top: 70px;
}
.content-container {
margin: 0 125px;
}
#top-link.affix {
position: absolute;
bottom: 10px;
left: 10px;
}
</style>
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With