Skip to content

Instantly share code, notes, and snippets.

@eltonmesquita
Created September 16, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eltonmesquita/96065060e7be48b5ca6546454cb9d1be to your computer and use it in GitHub Desktop.
Save eltonmesquita/96065060e7be48b5ca6546454cb9d1be to your computer and use it in GitHub Desktop.
On viewport - Vanilla
/* Vanilla Version */
var Onviewport = function(el, elClass, offset, callback) {
var els = document.querySelectorAll(el),
top,
this_top,
height;
if(!offset) { var offset = 0; }
// handle event
window.addEventListener("optimizedScroll", function() {
for(var e = 0; e < els.length; e++) {
top = document.documentElement.scrollTop || document.body.scrollTop;
this_top = els[e].getBoundingClientRect().top - offset;
height = els[e].getBoundingClientRect().height;
// Scrolled within current section
if (top >= this_top && !els[e].classList.contains(elClass)) {
els[e].classList.add(elClass)
if (typeof callback == "function") callback(el);
}
}
});
/*
requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
From: https://gist.github.com/paulirish/1579671
MIT license
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// Event throttle
;(function() {
var throttle = function(type, name, obj) {
var obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle ("scroll", "optimizedScroll");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment