Skip to content

Instantly share code, notes, and snippets.

@sourovroy
Last active March 29, 2018 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sourovroy/28e8ea6ffe27bd8cc338469d0d9928da to your computer and use it in GitHub Desktop.
Save sourovroy/28e8ea6ffe27bd8cc338469d0d9928da to your computer and use it in GitHub Desktop.
Simple back to top
/* JavaScript */
jQuery(document).ready(function($){
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.cd-top');
//hide or show the "back to top" link
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
<!-- HTML -->
<a href="#0" class="cd-top"><i class="fa fa-chevron-up" aria-hidden="true"></i></a>
/* CSS */
a.cd-top {
display: block;
height: 40px;
width: 40px;
position: fixed;
bottom: 40px;
right: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
overflow: hidden;
white-space: nowrap;
visibility: hidden;
opacity: 0;
background-color: #42AAE0;
-webkit-transition: opacity 0.3s 0s, visibility 0s 0.3s;
-moz-transition: opacity 0.3s 0s, visibility 0s 0.3s;
transition: opacity 0.3s 0s, visibility 0s 0.3s;
text-align: center;
line-height: 38px;
color: #fff;
font-size: 18px;
}
a.cd-top.cd-is-visible, .cd-top.cd-fade-out, .no-touch .cd-top:hover {
-webkit-transition: opacity .3s 0s, visibility 0s 0s;
-moz-transition: opacity .3s 0s, visibility 0s 0s;
transition: opacity .3s 0s, visibility 0s 0s;
}
a.cd-top.cd-is-visible {
visibility: visible;
opacity: 1;
}
.no-touch a.cd-top:hover {
background-color: #42AAE0;
opacity: 1;
}
a.cd-top:hover, a.cd-top:focus {
color: #fff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment