Created
July 31, 2018 21:26
-
-
Save zkreations/e283c9509fa252eaad8b5a4adccba160 to your computer and use it in GitHub Desktop.
ScrollToTop animation using pure javascript (not jquery)
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
/*! | |
=> Plugin: scrollToTop | |
=> by zkreations.com | Daniel Abel | |
*/ | |
/*reset button*/ | |
.scrollToTop { | |
outline: none; | |
border: none; | |
font-size: 14px; | |
cursor: pointer; | |
} | |
.scrollToTop svg { | |
display: block; | |
} | |
/*style*/ | |
.scrollToTop { | |
position: fixed; | |
opacity: 0; | |
visibility: hidden; | |
transition: transform .3s, visibility .3s, opacity .3s, background .3s; | |
transform: translateY(-2em); | |
} | |
.scrollToTop.visible { | |
visibility: visible; | |
opacity: 1; | |
transform: translateY(0); | |
} | |
/*Personalize*/ | |
.scrollToTop svg { | |
fill: #FFFFFF; | |
} | |
.scrollToTop { | |
background-color: rgba(0, 0, 0, 0.85); | |
box-shadow: 0 1px 2px rgba(0,0,0,0.5), 0 1px 7px rgba(0,0,0,0.25); | |
bottom: 1em; | |
right: 1em; | |
color: #fff; | |
padding: .5em; | |
border-radius: 4px; | |
} | |
.scrollToTop:hover { | |
background-color: rgba(0, 0, 0, 0.95); | |
} |
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
// Plugin: scrollToTop | |
// by zkreations.com | Daniel Abel | |
var scrollToTop = (function() { | |
var showButton = 600, | |
scrollSpeed = 1000; | |
function scrollTop(b) { | |
function a(d) { | |
c += Math.PI / (b / (d - e)); | |
c >= Math.PI && window.scrollTo(0, 0); | |
0 !== window.scrollY && (window.scrollTo(0, Math.round(scrollTime + scrollTime * Math.cos(c))), e = d, window.requestAnimationFrame(a)) | |
} | |
var scrollTime = window.scrollY / 2, | |
c = 0, | |
e = performance.now(); | |
window.requestAnimationFrame(a) | |
} | |
var scrollPosition = window.scrollY, | |
scrollButton = document.getElementById("scrollToTop"); | |
window.addEventListener("scroll", function() { | |
scrollPosition = window.scrollY; | |
showButton < scrollPosition ? scrollButton.classList.add("visible") : scrollButton.classList.remove("visible") | |
}); | |
scrollButton.onclick = function() { | |
scrollTop(scrollSpeed) | |
} | |
})(); | |
// HTML example : | |
// | |
// <button id="scrollToTop" class="scrollToTop"> | |
// <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 24 24"> | |
// <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/> | |
// <path d="M0 0h24v24H0z" fill="none"/> | |
// </svg> | |
// </button> | |
// | |
// Enjoy! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment