Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created June 20, 2015 05:36
Show Gist options
  • Select an option

  • Save z-------------/71e564c636d505100c3a to your computer and use it in GitHub Desktop.

Select an option

Save z-------------/71e564c636d505100c3a to your computer and use it in GitHub Desktop.
arachnid.js
var arachnid = {};
arachnid.init = function(elems, callback) {
var a = {
callback: (typeof callback === "function" ? callback : function(e) { console.log(e) }),
elems: []
};
var sectionHistory = [null, null];
if (Array.isArray(elems)) {
a.elems = elems;
} else if (elems instanceof NodeList || elems instanceof HTMLCollection) {
a.elems = [].slice.call(elems); // turn into array
} else if (typeof elems === "string") {
a.elems = [].slice.call(document.querySelectorAll(elems));
}
a.getCurrentSection = function() {
var contenders = [];
for (var s = 0; s < a.elems.length; s++) {
var elem = a.elems[s];
var item = {
elem: elem,
onScreen: (function(elem){
// elem array
var eArr = [];
for (var e = elem.offsetTop; e <= elem.offsetTop + elem.offsetHeight; e++) {
eArr.push(e);
}
// screen array
var sArr = [];
for (var s = window.scrollY; s <= window.scrollY + window.innerHeight; s++) {
sArr.push(s);
}
// calculate overlap
var overlap = [];
eArr.forEach(function(v){
if (sArr.indexOf(v) !== -1) {
overlap.push(v)
}
});
return (overlap[overlap.length - 1] - overlap[0])
})(elem)
};
contenders.push(item);
}
contenders = contenders.filter(function(item){
return isFinite(item.onScreen);
});
contenders.sort(function(a, b){
if (a.onScreen > b.onScreen) {
return -1;
} else if (b.onScreen > a.onScreen) {
return 1;
}
});
if (contenders[0]) {
return contenders[0].elem;
}
return null;
};
a.updateSectionHistory = function() {
sectionHistory[1] = sectionHistory[0];
sectionHistory[0] = a.getCurrentSection();
return;
};
a.compareSectionHistory = function() {
if (sectionHistory[0] === sectionHistory[1]) {
return false;
}
return true;
};
a.interval = setInterval(function() {
a.updateSectionHistory();
if (a.compareSectionHistory()) {
a.callback(sectionHistory[0]);
}
}, 50);
return a;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment