Skip to content

Instantly share code, notes, and snippets.

@skorotkiewicz
Created December 8, 2016 15:25
Show Gist options
  • Save skorotkiewicz/817da75b19a3689831d85092ceaf99b5 to your computer and use it in GitHub Desktop.
Save skorotkiewicz/817da75b19a3689831d85092ceaf99b5 to your computer and use it in GitHub Desktop.
back to top button
<!-- version: 1.3 (2013/12/01) - added lines: 46-51 (animated version) -->
<!-- version: 1.2 (2013/01/28) - edited line: 41 (added .stop) -->
<!-- ---------- HTML ---------- -->
..
<header>
...
<nav>..</nav>
...
</header>
...
<a href="#" id="archer"></a>
...
<!-- ---------- /HTML ---------- -->
<!-- ---------- CSS ---------- -->
<style type="text/css">
#archer{
display: none; /* we dont show the button while menu is visible */
width: 80px;
height: 80px;
background: url(/images/backToTop.png) center center no-repeat;
position: fixed;
bottom: 20px;
right: 20px;
z-index: 999; /* to be at the top of all elements */
}
</style>
<!-- ---------- /CSS ---------- -->
<!-- ---------- JS ---------- -->
<script type="text/javascript">
$(window).scroll(function(){ //after scroll
var docViewTop = $(window).scrollTop(); //get top of visible part of page
var elemTop = $('header nav').offset().top; //get top of menu/navigation
if ( !( elemTop >= docViewTop ) ){ //if top of navigation is not in visible part of page
$('#archer').fadeIn(); //show the 'back to top' button
}
else{
$('#archer').stop().fadeOut(); //else dont show the button (or hide if its showed)
}
});
$('#archer').click(function(){ //click on button cause..
$('html, body').animate({
scrollTop: $('body').offset().top //..the window is scrolling to top
}, 200);
return false; //'return false' to dont write char '#' to the end of an URL in the browser
});
//or non animate version:
//$('#archer').click(function(){ //click on button cause..
// $(window).scrollTop(0); //..the window is scrolling to top
// return false; //'return false' to dont write char '#' to the end of an URL in the browser
//});
</script>
<!-- ---------- /JS ---------- -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment