Skip to content

Instantly share code, notes, and snippets.

@vejei
Created December 28, 2017 12:23
Show Gist options
  • Save vejei/669b8b7a5cd546165b9dbbf291937845 to your computer and use it in GitHub Desktop.
Save vejei/669b8b7a5cd546165b9dbbf291937845 to your computer and use it in GitHub Desktop.
jQuery back to top
<!DOCTYPE html>
<html>
<head>
<title>Back to top</title>
<style type="text/css">
#back-to-top {
position: fixed;
bottom: 40px;
right: 40px;
z-index: 9999;
width: 32px;
height: 32px;
text-align: center;
line-height: 30px;
background: #f5f5f5;
color: #444;
cursor: pointer;
border: 0;
border-radius: 2px;
text-decoration: none;
transition: opacity 0.2s ease-out;
opacity: 0;
}
#back-to-top:hover {
background: #e9ebec;
}
#back-to-top.show {
opacity: 1;
}
#content {
height: 2000px;
}
</style>
</head>
<body>
<div id="content">Scroll &darr;</div>
<a href="#" id="back-to-top" title="Back to top">&uarr;</a>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
if ($('#back-to-top').length) {
var scrollTrigger = 200, // px
backToTop = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > scrollTrigger) {
$('#back-to-top').addClass('show');
} else {
$('#back-to-top').removeClass('show');
}
};
backToTop();
$(window).on('scroll', function () {
backToTop();
});
$('#back-to-top').on('click', function (e) {
e.preventDefault();
$('html,body').animate({
scrollTop: 0
}, 200);
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment