forked from ericbutler555/plain-js-slidetoggle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslideToggle.js
78 lines (62 loc) · 2.76 KB
/
slideToggle.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
/* plain JS slideToggle https://github.com/ericbutler555/plain-js-slidetoggle */
HTMLElement.prototype.slideToggle = function(duration, callback) {
if (this.clientHeight === 0) {
_s(this, duration, callback, true);
} else {
_s(this, duration, callback);
}
};
HTMLElement.prototype.slideUp = function(duration, callback) {
_s(this, duration, callback);
};
HTMLElement.prototype.slideDown = function (duration, callback) {
_s(this, duration, callback, true);
};
function _s(el, duration, callback, isDown) {
if (typeof duration === 'undefined') duration = 400;
if (typeof isDown === 'undefined') isDown = false;
el.style.overflow = "hidden";
if (isDown) el.style.display = "block";
var elStyles = window.getComputedStyle(el);
var elHeight = parseFloat(elStyles.getPropertyValue('height'));
var elPaddingTop = parseFloat(elStyles.getPropertyValue('padding-top'));
var elPaddingBottom = parseFloat(elStyles.getPropertyValue('padding-bottom'));
var elMarginTop = parseFloat(elStyles.getPropertyValue('margin-top'));
var elMarginBottom = parseFloat(elStyles.getPropertyValue('margin-bottom'));
var stepHeight = elHeight / duration;
var stepPaddingTop = elPaddingTop / duration;
var stepPaddingBottom = elPaddingBottom / duration;
var stepMarginTop = elMarginTop / duration;
var stepMarginBottom = elMarginBottom / duration;
var start;
function step(timestamp) {
if (start === undefined) start = timestamp;
var elapsed = timestamp - start;
if (isDown) {
el.style.height = (stepHeight * elapsed) + "px";
el.style.paddingTop = (stepPaddingTop * elapsed) + "px";
el.style.paddingBottom = (stepPaddingBottom * elapsed) + "px";
el.style.marginTop = (stepMarginTop * elapsed) + "px";
el.style.marginBottom = (stepMarginBottom * elapsed) + "px";
} else {
el.style.height = elHeight - (stepHeight * elapsed) + "px";
el.style.paddingTop = elPaddingTop - (stepPaddingTop * elapsed) + "px";
el.style.paddingBottom = elPaddingBottom - (stepPaddingBottom * elapsed) + "px";
el.style.marginTop = elMarginTop - (stepMarginTop * elapsed) + "px";
el.style.marginBottom = elMarginBottom - (stepMarginBottom * elapsed) + "px";
}
if (elapsed >= duration) {
el.style.height = "";
el.style.paddingTop = "";
el.style.paddingBottom = "";
el.style.marginTop = "";
el.style.marginBottom = "";
el.style.overflow = "";
if (!isDown) el.style.display = "none";
if (typeof callback === 'function') callback();
} else {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}