This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonscrollclass.js
89 lines (71 loc) · 2.01 KB
/
onscrollclass.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* OnScrollClass.js v0.1.0
* https://github.com/tu4mo/onscrollclass.js
*
* Copyright © 2016 tu4mo
*/
(function(window, document) {
'use strict';
var onScrollElements = [];
/**
* Gets the elements and adds the EventListener.
*/
function init() {
onScrollElements = getElements();
if (onScrollElements.length > 0) {
// Fire once in case element is already in view
checkElements();
// Listen for scrolling
window.addEventListener('scroll', checkElements);
}
}
/**
* Returns a list of elements with data-onscrollclass attribute.
*
* @return {Array} Array of elements.
*/
function getElements() {
var elements = [];
// Get NodeList of elements with data-onscrollclass attribute
var elementsNodeList = document.querySelectorAll('[data-onscrollclass]');
// Convert NodeList to array
for (var i = elementsNodeList.length; i--; elements.unshift(elementsNodeList[i]));
return elements;
}
/**
* Goes through all the onScrollElements and checks if they are in view.
*/
function checkElements() {
var onScrollElementsLength = onScrollElements.length;
if (onScrollElementsLength > 0) {
for (var i = onScrollElementsLength - 1; i > -1; i--) {
// Get element's onscrollclass
var element = onScrollElements[i];
var className = element.getAttribute('data-onscrollclass');
if (isElementInView(element)) {
// Add class to element
element.classList.add(className);
// Remove element from onScrollElements
onScrollElements.splice(i, 1);
}
}
} else {
// Remove EventListener if there are no more elements
window.removeEventListener('scroll', scroll);
}
}
/**
* Checks if the element is in view.
*
* @param {Element} element The element to check for.
* @return {Boolean} Returns whether element is in view.
*/
function isElementInView(element) {
var rect = element.getBoundingClientRect();
return (
window.pageYOffset + window.innerHeight >= rect.top + window.pageYOffset
);
}
// Fire up
init();
})(window, document);