JSFiddle - React, Tailwind, and code Playground

by Konstantin Cryman

JavaScript

var ScrollListener = (function(){

  function ScrollListener( min, max ){
    this.min = min/100 || 0;
    this.max = max/100 || 0.1;

    console.log( window );

    this.element = window;

    this.alpha = false;
    this.lastAlpha = false;

    this.scrollPosition = 0;
    this.listener = function(){};

    this.init();
  }

  ScrollListener.prototype.scroll = function( func ){
    this.listener = func;
    return this;
  }

  ScrollListener.prototype.getScroll = function(){
    return this.scrollPosition;
  };

  ScrollListener.prototype.update = function(){
    var scroll = this.getScroll();
    if ( scroll < this.min ) scroll = this.min;
    if ( scroll > this.max ) scroll = this.max;
    var alpha = ( this.max - scroll ) / ( this.max - this.min );
    return 1- alpha;
  };

  ScrollListener.prototype.scrollEvent = function(){
    var h = ( (document.height !== undefined) ? document.height : document.body.offsetHeight) - this.element.innerHeight;
    this.scrollPosition = this.element.scrollY /  h;
    this.alpha = this.update();
    if( !this.lastAlpha ) {
      this.lastAlpha = this.alpha;
      this.listener( this.alpha );
    } else {
      if (this.alpha != this.lastAlpha) {
        this.listener( this.alpha );
      }
    }
  };

  ScrollListener.prototype.init = function(){
    var self = this;
    self.scrollListen = function(){
      self.scrollEvent();
    }

    this.element.addEventListener( 'scroll', self.scrollListen, false );
    this.scrollEvent();
  };

  ScrollListener.prototype.destroy = function(){
    this.element.removeListener( 'scroll', this.scrollListen );
  };

  return ScrollListener;

})();


var scrollListener1 = new ScrollListener( 10, 70 ).scroll( function( alpha ){
  
});