How can I animate a height change after changing the height with javascript?
Advertisement
Answer
Do you can use Tranform scale and transition, in this case scaleY()
. See an example:
JavaScript
x
93
93
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<style>
5
html {
6
text-align: center;
7
font-size: 14px;
8
}
9
10
body {
11
font-size: 1.6rem;
12
}
13
14
h1 {
15
font-size: 4rem;
16
line-height: 5rem;
17
margin: 4rem;
18
}
19
20
.container {
21
margin: 4rem auto;
22
width: 90%;
23
max-width: 60rem;
24
}
25
p {
26
line-height: 2.2rem;
27
}
28
29
p:not {
30
margin-bottom: 2rem;
31
}
32
33
.btn {
34
bg: #09c;
35
background: #09c;
36
border: 0;
37
color: #fff;
38
cursor: pointer;
39
display: block;
40
font-size: 1.4rem;
41
padding: 1.5rem 3rem;
42
transition: background .2s;
43
width: 100%;
44
}
45
46
.btn:hover, .btn:focus {
47
background: darken(bg, 15%);
48
}
49
50
.btn:in {
51
background: darken(bg, 50%);
52
}
53
54
.box {
55
background: #e5e5e5 ;
56
margin-left: auto;
57
margin-right: auto;
58
padding: 3rem;
59
text-align: left;
60
transform: scaleY(0);
61
transition: transform .3s;
62
transform-origin: top left;
63
}
64
65
.box.in {
66
transform: scaleY(1);
67
}
68
</style>
69
</head>
70
<body>
71
<h1>Animated height with CSS transitions</h1>
72
73
<div class='container'>
74
<button class='btn'>Click me</button>
75
<div class='box'>
76
<p>
77
Some text here!
78
</p>
79
</div>
80
</div>
81
<script>
82
document.querySelector('.btn')
83
.addEventListener('click', function (event) {
84
85
event.currentTarget.classList.toggle('in')
86
87
document.querySelector('.box')
88
.classList.toggle('in')
89
})
90
</script>
91
<body>
92
<html>
93