My approach to styling the spans involved changing them to display inline block for better control, with added width and text alignment properties on the target span.
I also implemented a CSS class called "reveal" that triggers an animation sliding down the content, which is added dynamically in the showval function along with an event listener to remove it post-animation completion.
Moreover, I switched from using getElementsByClassName to querySelector for more efficient targeting.
To determine the widest word, I looped through the content and placed each in a temporary element to calculate the maximum width considering varying letter widths.
var para_values = [
{
content: "BRAND "
},
{
content: "MISSION"
}
];
const getMaxWidth = () => {
let maxWidth = 0;
let temp = document.createElement("span");
temp.classList.add("ib");
document.body.append(temp)
para_values.forEach((e) => {
temp.textContent = e.content;
if(temp.offsetWidth > maxWidth){
maxWidth = temp.offsetWidth;
}
});
temp.remove()
return maxWidth;
}
const spanWidth = getMaxWidth();
const wordEle = document.querySelector(".header-para");
wordEle.style.width = spanWidth + "px";
function showVal(index) {
wordEle.innerHTML = para_values[index].content;
wordEle.classList.add("reveal")
}
showVal(0);
function textChange() {
var index = 0;
setInterval(() => {
index = index + 1;
if (index == para_values.length) {
index = 0;
}
showVal(index)
}, 4000)
}
textChange();
wordEle.addEventListener("animationend", (event) => { wordEle.classList.remove("reveal")});
.header-para {
height: 60px;
background-color: rgb(51, 235, 198);
text-align:center;
}
.ib,
.text-overlay span {
color: black;
font-size: 56px;
display:inline-block;
}
.reveal {
animation: slide-down 1s;
}
@keyframes slide-down {
from {
transform: translateY(-50px);
opacity: 0;
}
to {
opacity: 1;
transform: translateY(0px);
animation: linear;
}
}
<div class="text-overlay">
<span>Your</span> <span class="header-para"></span><span>Understand</span>
</div>