Smooth Scroll to Top in JavaScript

Smooth Scroll to Top in JavaScript
Code Snippet: Scrolling Up Button
Author: Wiktor
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 2,679
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a smooth scroll to the top button. It dynamically adds back to the top page button on a webpage. You just need to add JS function to your web project, then this plugin dynamically adds back to the top button.

It comes with following features:

  • 3 animate modes: [“normal”|”linear”|false]
  • Customize your animation with available settings – make it snappy or fluent
  • Double click to skip the animation
  • Every next single click adds initial speed
  • Stop scroll animation by dragging down the scroll bar
  • Stop scroll animation by mouse wheel down
  • Animated button fade-in-out on scroll

How to Create Smooth Scroll to Top in JavaScript

1. First of all, add the following CSS styles to your project:

/* CSS */
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body{
  font-family: 'Open Sans', sans-serif;
  font-size: 1.2rem;
  line-height: 2rem;
  height: 100%;
  position: relative;
}

.scroll-button{
  box-sizing: border-box;
  font-size: 1.2rem;
  line-height: 2rem;
  padding: 5px;
  width: 80px;
  height: 80px;
  right: 20px;
  bottom: 20px;
  visibility: visible;
  filter: alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50);
  opacity: 0.5;
  cursor: pointer;
  transition: all 1.2s;
  -webkit-transition: all 1.2s;
  -moz-transition: all 1.2s;
  -ms-transition: all 1.2s;
  -o-transition: all 1.2s;
}

/* STYLE BUTTON 1 - filled in */
/* .scroll-button{
  background: rgb(249, 104, 211);
  border: none;
  color: white;
} */

/* STYLE BUTTON 2 - only outlines */
.scroll-button{
  background: none;
  border: solid 2px rgb(210, 104, 211);
  color: rgb(249, 104, 211);
}

/* SHAPE BUTTON 1 - round */
/* .scroll-button{
  border-radius: 50%;
} */

/* SHAPE BUTTON 2 - square */
.scroll-button{
  border-radius: 0%;
}

/* POSITION BUTTON 1 - on the bottom of the screen */
.scroll-button{
  position: fixed;
}

/* POSITION BUTTON 2 - on the bottom of the page */
/* .scroll-button{
  position: absolute;
} */





.scroll-button:hover{
  filter: alpha(opacity=100);
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
}

.scroll-button--hidden{
  filter: alpha(opacity=0);
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  visibility: hidden;
}

3. Then, add the following JavaScript code and done.

// PURE JAVASCRIPT "Scroller" CLASS (OOP)
/*
* Author: Wiktor Liszkiewicz
*/

function Scroller(options) {
  this.options = options;
  this.button = null;
  this.stop = false;
}

Scroller.prototype.constructor = Scroller;

Scroller.prototype.createButton = function() {

  this.button = document.createElement('button');
  this.button.classList.add('scroll-button');
  this.button.classList.add('scroll-button--hidden');
  this.button.textContent = "^";
  document.body.appendChild(this.button);
}
  
Scroller.prototype.init = function() {
  this.createButton();
  this.checkPosition();
  this.click();
  this.stopListener();
}

Scroller.prototype.scroll = function() {
  if (this.options.animate == false || this.options.animate == "false") {
    this.scrollNoAnimate();
    return;
  }
  if (this.options.animate == "normal") {
    this.scrollAnimate();
    return;
  }
  if (this.options.animate == "linear") {
    this.scrollAnimateLinear();
    return;
  }
}
Scroller.prototype.scrollNoAnimate = function() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
Scroller.prototype.scrollAnimate = function() {
  if (this.scrollTop() > 0 && this.stop == false) {
    setTimeout(function() {
      this.scrollAnimate();
      window.scrollBy(0, (-Math.abs(this.scrollTop())/this.options.normal['steps']));
    }.bind(this), (this.options.normal['ms']));
  }
}
Scroller.prototype.scrollAnimateLinear = function() {
  if (this.scrollTop() > 0 && this.stop == false) {
    setTimeout(function() {
      this.scrollAnimateLinear();
      window.scrollBy(0, -Math.abs(this.options.linear['px']));
    }.bind(this), this.options.linear['ms']);
  }
}

Scroller.prototype.click = function() {
  
  this.button.addEventListener("click", function(e) {
    e.stopPropagation();
      this.scroll();
  }.bind(this), false);
  
  this.button.addEventListener("dblclick", function(e) {
    e.stopPropagation();
      this.scrollNoAnimate();
  }.bind(this), false);
  
}

Scroller.prototype.hide = function() {
  this.button.classList.add("scroll-button--hidden");
}

Scroller.prototype.show = function() {
  this.button.classList.remove("scroll-button--hidden");
}

Scroller.prototype.checkPosition = function() {
  window.addEventListener("scroll", function(e) {
    if (this.scrollTop() > this.options.showButtonAfter) {
      this.show();
    } else {
      this.hide();
    }
  }.bind(this), false);
}

Scroller.prototype.stopListener = function() {
  
  // stop animation on slider drag
  var position = this.scrollTop();
  window.addEventListener("scroll", function(e) {
    if (this.scrollTop() > position) {
      this.stopTimeout(200);
    } else {
      //...
    }
    position = this.scrollTop();
  }.bind(this, position), false);

  // stop animation on wheel scroll down
  window.addEventListener("wheel", function(e) {
    if(e.deltaY > 0) this.stopTimeout(200);
  }.bind(this), false);
}

Scroller.prototype.stopTimeout = function(ms){
   this.stop = true;
         // console.log(this.stop); //
   setTimeout(function() {
     this.stop = false;
           console.log(this.stop); //
   }.bind(this), ms);
}

Scroller.prototype.scrollTop = function(){
   var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  return curentScrollTop;
}



// ------------------- USE EXAMPLE ---------------------
// *Set options
var options = {
  'showButtonAfter': 200, // show button after scroling down this amount of px
  'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed
  // easy out effect
  'normal': { // applys only if [animate: normal] - set scroll loop "distanceLeft"/"steps"|"ms"
    'steps': 15, // more "steps" per loop => slower animation
    'ms': 1000/60 // less "ms" => quicker animation, more "ms" => snapy
  },
  // linear effect
  'linear': { // applys only if [animate: linear] - set scroll "px"|"ms"
    'px': 80, // more "px" => quicker your animation gets
    'ms': 1000/60 // Less "ms" => quicker your animation gets, More "ms" =>
  }, 
};
// *Create new Scroller and run it.
var scroll = new Scroller(options);
scroll.init();

That’s all! hopefully, you have successfully integrated this smooth scroll to top code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X