Skip to content

Instantly share code, notes, and snippets.

@AskChanDra
Created October 15, 2020 07:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AskChanDra/a9cad1af31079c10781c05a9f3403b06 to your computer and use it in GitHub Desktop.
Save AskChanDra/a9cad1af31079c10781c05a9f3403b06 to your computer and use it in GitHub Desktop.
Scroll to Top

Scroll to Top code :

<style>
/* Scroll function element */
.scroll {
  position: fixed;
  bottom: 25px;
  right: 25px;
  width: 70px;
  height: 70px;
  border-radius: 50%;
  border: none;
  background-color: rgba(237, 237, 237, 0.9);
  transition: all 150ms ease;
  transform: scale(0);
	outline: none;
	cursor: pointer;
}
.scroll:focus {
  outline: none;
}

.fa-sort-up {
  color: #f78ca0;
  margin-top: 15px;
}

.scroll:hover .fa-sort-up {
  animation: jump 800ms infinite;
}

@keyframes jump {
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0);
  }
}
/* End scroll function element */


@media screen and (max-width: 1300px) {
	.fa-sort-up {
  animation: jump 800ms infinite;
}
}
</style>
 <!-- Scroll function element -->
  <button class="scroll"><i class="fas fa-sort-up fa-3x"></i></button>
  <!-- End scroll function element -->
  <script>
    const btn = document.querySelector('.scroll');

    btn.addEventListener('click', function() {
    scroll(0, 200);
    })

    window.onscroll = function showHide() {
    if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
        btn.style.transform = 'scale(1)';
    }
    else {
        btn.style.transform = 'scale(0)';
    }
    }

    function scroll (target, duration) {
    if (duration <= 0) {return};
    let difference = target - document.documentElement.scrollTop;
    let speed = difference / duration * 10;
    setTimeout(function() {
        document.documentElement.scrollTop += speed;
        if (document.documentElement.scrollTop == target) {return};
        scroll(target, duration - 10);
    }, 10);
    }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment