Created
July 9, 2020 18:54
-
-
Save chris-castillo-dev/62199a47874d04c6dc9f2673f472c63e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Adds 'Back to top' functionality to an element with the ID 'back-to-top' | |
* @example | |
* 1. Create a link-wrapper with ID 'back-to-top' | |
* 2. Add an icon inside the link-wrapper such as an arrow | |
* 3. Set position fixed: bottom right | |
* 4. Set opacity to 0 | |
*/ | |
class BackToTop { | |
constructor() { | |
this.$backToTop = $('#back-to-top'); | |
this.toggleDistance = 50; | |
if( this.$backToTop.length > 0 ){ | |
this.init(); | |
} | |
} | |
init() { | |
window.onscroll = () => this.scrollFunction(); | |
this.$backToTop.on( 'click', () => this.scrollToTop() ); | |
} | |
scrollFunction() { | |
if (document.body.scrollTop > this.toggleDistance) { | |
this.$backToTop.addClass('active'); | |
} else { | |
this.$backToTop.removeClass('active'); | |
} | |
} | |
scrollToTop(){ | |
window.scrollTo(0, 0); | |
} | |
} | |
export default BackToTop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment