I’m looking for an effect like the primary one on this page https://sendgrid.com/
The page shows a centered sentence, a word is replaced, the sentence parts left and right to the word, smoothly readjust position according to the new word width.
JavaScript
x
8
1
<body>
2
<h1>
3
This animation is
4
<span id="swappable">awesome</span>
5
don't you think?
6
</h1>
7
</body>
8
JavaScript
1
9
1
body {
2
display: flex;
3
justify-content: center;
4
}
5
6
#swappable {
7
display: inline-block;
8
}
9
JavaScript
1
8
1
const swappables = ["bad", "great", "fantastic", "boring"];
2
3
let index = 0;
4
setInterval(() => {
5
document.getElementById("swappable").innerHTML = swappables[index];
6
index = index == swappables.length - 1 ? 0 : index + 1;
7
}, 3000);
8
This code makes the parts snap into place after a word is replaced but
How can I achieve this smooth transition?
Advertisement
Answer
JavaScript
1
12
12
1
document.addEventListener('DOMContentLoaded',()=>{
2
const stringsCont = document.querySelector('#strings-cont');
3
const strings = [stringsCont.querySelectorAll('.string')];
4
let active = 0;
5
next = () =>{
6
strings.forEach((s,i) => i===active?s.classList.add('active'):s.classList.remove('active'));
7
stringsCont.style.width = strings[active].offsetWidth+'px';
8
active = (active+1)%strings.length;
9
}
10
setInterval(next, 3000);
11
setTimeout(next,0)
12
});
JavaScript
1
47
47
1
h1 {
2
font-family: sans-serif;
3
font-size: 16px;
4
text-align: center;
5
font-weight: normal;
6
display: flex;
7
align-items: center;
8
justify-content: center;
9
}
10
#strings-cont{
11
position: relative;
12
display: inline-flex;
13
transition: width .3s ease;
14
justify-content: center;
15
}
16
.string {
17
font-weight: bold;
18
transition: opacity .3s ease, top .3s ease;
19
position: absolute;
20
opacity:0;
21
left: 50%;
22
top: 100%;
23
transform: translateX(-50%);
24
white-space: nowrap;
25
}
26
.string:before {
27
content: '';
28
position: absolute;
29
top: 100%;
30
left:0;
31
height: 3px;
32
width: 0;
33
background-color: violet;
34
}
35
.string.active {
36
transition: opacity .3s ease;
37
opacity:1;
38
position: static;
39
transform: translateX(0);
40
left:0;
41
top:0;
42
}
43
.string.active:before {
44
width: 100%;
45
transition: all 2.7s ease;
46
transition-delay: .3s;
47
}
JavaScript
1
10
10
1
<h1>
2
Send Email
3
<span id="strings-cont" style="width:0">
4
<span class="string">Lorem Ipsum</span>
5
<span class="string">Dolor Sit Ammet</span>
6
<span class="string">Consectetur Adipiscing Elit</span>
7
<span class="string">Sed Do Eiusmod</span>
8
</span>
9
With Confidence
10
</h1>