Skip to content

Instantly share code, notes, and snippets.

@motionharvest
Last active February 6, 2020 16:20
Show Gist options
  • Save motionharvest/e0ab725d842b8834b193d1daf4ac13df to your computer and use it in GitHub Desktop.
Save motionharvest/e0ab725d842b8834b193d1daf4ac13df to your computer and use it in GitHub Desktop.
VectorScrolling rewrite for 2020. Only 350bytes Gzipped
/*
Copyright 2020 Aaron Sherrill
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var _vs = function(){
var clamp = function (val, min, max) {
return val > max ? max : val < min ? min : val;
}
var scale = function(num, in_min, in_max, out_min, out_max) {
let n = (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
return clamp(n, out_min, out_max);
}
function calculatePositions(){
for(var i = 0, vector, rect, a, b, offsetPerc; i < _vs.prototype.vectors.length; i++) {
vector = _vs.prototype.vectors[i];
rect = vector.element.getBoundingClientRect();
a = (window.innerHeight * vector.options[1]) - (rect.height * vector.options[0]);
b = (window.innerHeight * vector.options[3]) - (rect.height * vector.options[2]);
offsetPerc = scale(rect.top, a, b, 0, 1);
vector.callback(offsetPerc);
}
}
window.addEventListener("resize", calculatePositions);
return {
onScroll: function() {
requestAnimationFrame(function(){
calculatePositions()
});
},
add: function(element, options, callback) {
var id = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
_vs.prototype.vectors.push({
element: element,
options: options,
callback: callback,
id: id
});
calculatePositions();
return id;
},
remove: function(id) {
for(var i = 0; i <= _vs.prototype.vectors.length; i++) {
if(_vs.prototype.vectors[i].id == id) {
_vs.prototype.vectors.splice(i, 1);
break;
}
}
}
}
}
_vs.prototype.vectors = [];
var vs = new _vs();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment