Skip to content

Instantly share code, notes, and snippets.

@shabanovtg
Last active August 2, 2016 12:55
Show Gist options
  • Save shabanovtg/433b9f499179d2775e70 to your computer and use it in GitHub Desktop.
Save shabanovtg/433b9f499179d2775e70 to your computer and use it in GitHub Desktop.
back-to-top block
'use strict';
(function ($) {
var $body,
$window,
backToTop = {
init: function () {
this.$backToTop = $('#back-top');
this.$header = $('#header');
this.$footer = $('#footer');
if (this.$backToTop.length) {
this.bindEvents();
}
},
bindEvents: function () {
if (window.addEventListener) {
window.addEventListener('scroll', this.handlerScroll.bind(this), false);
window.addEventListener('resize', this.handlerResizer.bind(this), false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', this.handlerScroll.bind(this));
window.attachEvent('onresize', this.handlerResizer.bind(this));
}
$window.on('touchmove', this.handlerScroll.bind(this));
this.$backToTop.on('click', this.handlerClick.bind(this));
},
handlerClick: function(ev) {
ev.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 500);
},
handlerResizer: function () {
setTimeout(this.handlerScroll.bind(this), 500);
},
handlerScroll: function () {
var scrollTop = $window.scrollTop(),
navTop = 100,
footerTop = this.$footer.offset().top,
windowHeight = $window.height(),
b = 10;
this.$backToTop.toggleClass('_active', (scrollTop > navTop));
if (scrollTop + windowHeight > footerTop) {
b += windowHeight + scrollTop - footerTop;
}
this.$backToTop.css('bottom', b);
}
};
$(function () {
$body = $('body');
$window = $(window);
backToTop.init();
});
})(window.$j);
.back-top {
position: fixed;
bottom: 10px;
right: 10px;
z-index: 9;
width: 4rem;
height: 4rem;
color: #ffffff;
line-height: 4rem;
background-color: #222;
text-decoration: none;
text-align: center;
transition: opacity .2s ease-out;
opacity: 0;
&._active {
opacity: 1;
}
&:hover,
&:active,
&:focus,
&:visited {
color: #ffffff;
text-decoration: none;
}
}
<header id="header" class="header">
<div class="container"></div>
</header>
<section id="main" class="main">
<a href="#" id="back-top" class="back-top">▲</a>
</section>
<footer id="footer" class="footer">
<div class="container"></div>
</footer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment