Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active December 27, 2015 10:29
Show Gist options
  • Select an option

  • Save WebReflection/7311642 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/7311642 to your computer and use it in GitHub Desktop.
the most basic horizontal scroll handler I could think about … no abstraction, some magic happening, works with Android 2.X and all touch devices, might be improved for pointer events too when it comes to touch instead of mouse.
/*! (C) Andrea Giammarchi */
// @link https://gist.github.com/WebReflection/7311642
var HorizontalScroll = (function(UA, Math){
var
// this is horrible, unfortunately needed
bugged = /Android 4\.0/.test(UA),
// AFAIK no proper way to do feature in here detection :-(
preventsAllDefaults = /Android/.test(UA) &&
/Chrom(?:e|ium)/.test(UA),
// shortcut for happy minifiers
Prototype = HorizontalScroll.prototype,
// quicker shortcuts
abs = Math.abs,
max = Math.max,
min = Math.min,
gap = 15
;
// a very essential horizontal touch scroll handler
// @param the target which parent can scroll
// i.e. the <p> element within the scrollable container
// <div class="scrlable"><p></p></div>
// @param object with handlers
function HorizontalScroll(el, obj) {
if (!obj) obj = this;
// needs the original reference
this._el = el;
// and an element with an offset (mainly a Chrome problem)
while (!el.offsetHeight) el = el.parentNode;
addOrRemoveListeners(this, this._r = el, true);
// mark as working
this.disabled = false;
// by default, it really does nothing
// avoiding cheks per each call
this.onstart = obj.onstart || nothingToDoHere;
this.onchange = obj.onchange || nothingToDoHere;
this.onend = obj.onend || nothingToDoHere;
this.onclick = obj.onclick || nothingToDoHere;
if ('ontouchend' in document) {
// MS needs this to drop original scroll behavior
// others might want to enforce the scrolling
this._el.parentNode.style.cssText += [
';-ms-touch-action:none',
';touch-action:none',
';overflow:hidden'
].join('');
}
}
function nothingToDoHere(o_O){/*literally*/}
// helps adding or removing listeners
function addOrRemoveListeners(hs, el, add) {
var method = (add ? 'add' : 'remove') + 'EventListener';
el[method]('touchstart', hs, true);
el[method]('touchmove', hs, true);
el[method]('touchend', hs, true);
}
Prototype.clear = function clear() {
addOrRemoveListeners(this, this._r, false);
};
// entry point for the handler
Prototype.handleEvent = function handleEvent(e) {
if (this._vscrolling && e.type !== 'touchend') return;
if (preventsAllDefaults) e.preventDefault();
this[e.type](e);
};
Prototype.touchstart = function touchstart(e) {
// only if not scrolling yet
if (!this._scrolling) {
// remember first X in the page
// also the first Y to avoid undesired clicks
// even if slower to calculate,
// pageX is better than screenX
// due pixel density agnostic nature
// once the viewport has been set as mobile
e = e.touches[0];
this._x = e.pageX >> 0;
this._y = e.pageY >> 0;
this._diffY = 0;
this._t = 0;
this._l = 0;
// I don't care about multiple fingers for now
}
};
Prototype.touchmove = function touchmove(e) {
var
touch = e.touches[0],
pageX = touch.pageX >> 0
;
if (this._scrolling) {
// do not let it scroll by its own
e.preventDefault();
// do not propagate the action anywhere
e.stopPropagation();
// calculate the different x from
// the beginning of the action
e.x = pageX - this._diffX - this._x;
// however, Android 4.0 will ignore that
// reflecting the value if get but not the layout
if (bugged) {
this._p.style.marginLeft = max(
this._m,
min(0, e.x + this._l)
) + 'px';
this._e = e.x;
} else {
// change the scroll
this._p.scrollLeft = this._s - e.x;
}
// notify the scroll changed
this.onchange(e);
}
// verify if scrolling
else {
// calculate current diff from the first pageX/Y
this._diffX = pageX - this._x;
this._diffY = touch.pageY - this._y;
this._vscrolling = gap <= this._t++ || gap <= abs(this._diffY);
// if that's about 15 or more
this._scrolling = !this._vscrolling && gap <= abs(this._diffX);
// then it's scrolling
if (this._scrolling) {
e.preventDefault();
// grab the element that should scroll
this._p = this._el.parentNode;
// store initial scrolling value
this._s = this._p.scrollLeft;
if (bugged) {
if (!this._l) {
this._l = parseFloat(this._p.style.marginLeft || 0);
if (!this._l && this._p.scrollLeft) {
this._l = -this._p.scrollLeft;
this._p.scrollLeft = 0;
this._p.style.marginLeft = this._l + 'px';
}
// minimum margin left
// so it won't disappear from the screen
if (!this._m) {
this._m = this._p.clientWidth - this._p.scrollWidth;
}
}
this._s = -this._l;
}
// notify the action
this.onstart(e);
}
}
};
Prototype.touchend = function touchend(e) {
// and if there are no fingers anymore on the screen
if (!e.touches.length) {
// if it was scrolling
if (this._scrolling) {
// do not do anything by default
e.preventDefault();
// drop the parentNode reference
// so we have one less leak to think about
this._p = null;
if (bugged)
this._l = max(
this._m,
min(0, this._e + this._l)
)
;
// notify the end
this.onend(e);
} else if (!this._vscrolling) {
// no scrolled, this was a click intent
// bear in mind some browser might fire
// the click regardless the default has been prevented
this.onclick(e);
}
// reset them all
this._t = 0;
this._scrolling = false;
this._vscrolling = false;
}
};
// so it is possible to react differently
// through the marginLeft out there
HorizontalScroll.compat = bugged;
// the bare essential constructor
return HorizontalScroll;
}(navigator.userAgent, Math));
@WebReflection

Copy link
Copy Markdown
Author

HorizontalSnapScroll

Used in this page

var HorizontalSnapScroll = (function(ScrollHandler, SimpleKinetic){

  var IEMobile = !!(
        navigator.pointerEnabled || navigator.msPointerEnabled
      ),
      FALLBACK = /IEMobile\/9|webOS/g.test(navigator.userAgent),
      hasTimeoutRecovery = ScrollHandler.hasTimeoutRecovery,
      clearKinetic = hasTimeoutRecovery && !IEMobile ?
        function (self) {
          if (self._sk) {
            self._sk.cancel();
            self._sk = null;
          }
        } :
        function () {},
      HorizontalSnapScrollPrototype = HorizontalSnapScroll.prototype,
      abs = Math.abs,
      max = Math.max,
      min = Math.min,
      round = Math.round;

  function findElementIndex(el) {
    var i = 0;
    while(el.previousElementSibling) {
      el = el.previousElementSibling;
      i++;
    }
    return i;
  }

  function getBorderWidth(el) {
    var
      cs = getComputedStyle(el, null),
      left = parseFloat(cs.getPropertyValue('border-left-width')) || 0,
      right = parseFloat(cs.getPropertyValue('border-right-width')) || 0
    ;
    return left + right;
  }

  function snapTo(self, currentTarget, noAnim) {
    var
      el = self._el,
      width = getBorderWidth(el) +
              el.offsetWidth,
      movedAmount = abs(self.x),
      index = findElementIndex(el),
      next = self.x < 0 && el.nextElementSibling,
      previous = 0 < self.x && el.previousElementSibling,
      moving = width / 6 < movedAmount && !!(next || previous),
      adjust = self._adjust ? round(
        index * self._left / el.parentNode.children.length
      ) : self._left
    ;
    if (moving) {
      if (next) {
        self._el = next;
        index++;
      } else {
        self._el = previous;
        index--;
      }
    }
    if (hasTimeoutRecovery || FALLBACK) {
      if (noAnim) {
        currentTarget.scrollLeft =
          adjust + index * width - currentTarget.scrollLeft;
      } else {
        self._sk = new SimpleKinetic({
          context: currentTarget,
          onmove: function (x, y, dx, dy, ex, ey) {
            currentTarget.scrollLeft = x;
          }
        });
        self._sk.init(
          currentTarget.scrollLeft, 0,
          adjust + index * width - currentTarget.scrollLeft, 0,
          true, true
        );
      }
    } else {
      currentTarget.firstElementChild.style.marginLeft =
        -adjust + (index * -width) + 'px';
    }
  }

  HorizontalSnapScrollPrototype.oninit = function (e) {
    // only old FFOS might need e.preventDefault();
  };

  HorizontalSnapScrollPrototype.onstart = function (e) {
    var currentTarget = e.currentTarget;
    if (this.hscrolling) {
      e.preventDefault();
      clearKinetic(this);
      currentTarget.firstElementChild.classList.remove(this._toggle);
      if (hasTimeoutRecovery) {
        this.left = parseFloat(
          currentTarget.scrollLeft
        ) || 0;
        this.max =  getBorderWidth(currentTarget) +
                    currentTarget.scrollWidth -
                    currentTarget.offsetWidth;
      } else {
        this.left = parseFloat(
          currentTarget.firstElementChild.style.marginLeft
        ) || 0;
        this.max =  this.left -
                    getBorderWidth(currentTarget) -
                    currentTarget.scrollWidth +
                    currentTarget.offsetWidth;
      }
    }
  };

  HorizontalSnapScrollPrototype.onscroll = function (e) {
    var currentTarget = e.currentTarget,
        left = this.left,
        x = this.x;
    if (this.hscrolling) {
      e.preventDefault();
      if (hasTimeoutRecovery) {
        currentTarget.scrollLeft = (left - x);
      } else {
        currentTarget.firstElementChild.style.marginLeft =
          max(this.max, min(0, left + x)) + 'px';
      }
    }
  };

  HorizontalSnapScrollPrototype.onend = function (e) {
    var currentTarget = e.currentTarget;
    // if polyfilled, IEMobile might trigger this twice without target
    if (this.hscrolling && currentTarget) {
      e.preventDefault();
      currentTarget.firstElementChild.classList.add(this._toggle);
      if (this._snap) {
        setTimeout(
          snapTo,
          10,
          this,
          currentTarget
        );
      }
    }
  };

  HorizontalSnapScrollPrototype.clear = function(e) {
    if (FALLBACK) {
      el.removeEventListener('click', this.onclick);
    } else {
      clearKinetic(this);
      this._sh.clear(e);
      delete this._sh;
    }
  };

  // passed by default, can be configurable anyway
  HorizontalSnapScrollPrototype.onclick = Object;

  // default class to toggle (transition all)
  HorizontalSnapScrollPrototype._toggle = 't-all';

  function HorizontalSnapScroll(el, options) {
    var sh = FALLBACK ? {} : (
      this._sh = new ScrollHandler(el, this)
    );
    if (FALLBACK) {
      el.style.overflowX = 'auto';
    }
    if (options) {
      sh._snap =    !!options.snapTo;
      sh._left =    options.left || 0;
      sh._adjust =  !!options.adjust;
      sh._toggle =  options.toggle ||
                    HorizontalSnapScrollPrototype._toggle;
      sh.onclick =  options.onclick;
      if (FALLBACK && sh.onclick) {
        el.addEventListener('click', this.onclick = sh.onclick);
      }
      if (sh._snap) {
        sh._el = el.querySelector(options.snapTo);
        snapTo(sh, el, true);
      }
    }
  }

  return HorizontalSnapScroll;

}(ScrollHandler, SimpleKinetic));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment