-
Notifications
You must be signed in to change notification settings - Fork 1
/
tacky.js
61 lines (51 loc) · 1.71 KB
/
tacky.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
(function(){
'use strict'
function Tacky(el, opts) {
this.opts = Object.assign({}, {
tackedClass: 'tacked',
wrapperTag: 'div',
wrapperClass: 'tacky-wrapper',
handler: function(offsetY /*, tacked */) {
return offsetY <= 0;
}
}, opts);
this.element = el;
this.wrapperEl = document.createElement(this.opts.wrapperTag);
this.wrapperEl.classList.add(this.opts.wrapperClass);
this.tacked = false;
this._boundingRect = null;
this.element.parentNode.appendChild(this.wrapperEl);
this.element.remove();
this.wrapperEl.appendChild(this.element);
window.addEventListener('scroll', this.toggleTacked.bind(this));
return this;
}
Tacky.prototype.destroy = function() {
window.removeEventListener('scroll', this.toggleTacked.bind(this));
}
Tacky.prototype.toggleTacked = function() {
window.requestAnimationFrame(() => {
this._boundingRect = this.wrapperEl.getBoundingClientRect();
if (this.tacked) {
!this.opts.handler(this._boundingRect.top, this.tacked) && this.untack();
} else {
this.opts.handler(this._boundingRect.top, this.tacked) && this.tack();
}
});
}
Tacky.prototype.tack = function() {
this.wrapperEl.style.height = this._boundingRect.height + 'px';
this.element.remove();
document.body.appendChild(this.element);
this.element.classList.add(this.opts.tackedClass);
this.tacked = true;
}
Tacky.prototype.untack = function() {
this.element.remove();
this.element.classList.remove(this.opts.tackedClass);
this.wrapperEl.appendChild(this.element);
this.wrapperEl.style.height = null;
this.tacked = false;
}
window.Tacky = Tacky;
}())