-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.vanilla.js
31 lines (31 loc) · 1.14 KB
/
index.vanilla.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
export default (selector, option, stylesheet) => {
const attr = (selector + option).replace(/\W/g, '')
const features = {
partly: tag =>
tag.offsetTop - innerHeight < scrollY
&& tag.offsetTop - innerHeight + tag.offsetHeight < scrollY + tag.offsetHeight
&& scrollY < tag.offsetTop + tag.offsetHeight,
fully: tag =>
tag.offsetTop - innerHeight < scrollY
&& tag.offsetTop - innerHeight + tag.offsetHeight < scrollY
&& scrollY < tag.offsetTop
}
const result = Array.from(document.querySelectorAll(selector))
.reduce((output, tag, count) => {
if (features[option](tag)) {
output.add.push({tag: tag, count: count})
output.styles.push(
stylesheet.replace(
/:self|\$this|\[--self\]/g,
`[data-viewport-${attr}="${count}"]`
)
)
} else {
output.remove.push(tag)
}
return output
}, {add: [], remove: [], styles: []})
result.add.forEach(tag => tag.tag.setAttribute(`data-viewport-${attr}`, tag.count))
result.remove.forEach(tag => tag.setAttribute(`data-viewport-${attr}`, ''))
return result.styles.join('\n')
}