I’ve made a website with a simple typewriter effect, but the thing is, I want it to have exactly the number of steps, as there are letters in the word. I’ve tried to use the variable from Js in CSS, but it’s just not working, can someone please let me know how I can fix this ??
const text = document.getElementById("second-text");
const textLoad = () => {
setTimeout(() => {
text.textContent = "Freelancer";
let Steps = 10;
0); setTimeout(() => {
text.textContent = "Editor";
let Steps = 6;
4000); setTimeout(() => {
text.textContent = "Coder";
let Steps = 5;
8000);
}
textLoad(); setInterval(textLoad, 12000);
>body {
background: black;
margin: 0;
padding: 0;
font-family: "Poppins";
display: grid;
place-items: center;
height: 100vh;
width: 100%;
}
.container {
width: 300px;
overflow: hidden;
}
.container .text {
position: relative;
color: white;
font-size: 30px;
font-weight: 600;
align-items: start;
}
.container .first-text {
color: white;
}
.container .second-text::before {
content: "";
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: black;
border-left: 2px solid #4070f4;
animation: animate 4s steps(var(--Steps)) infinite;
}
@keyframes animate {
0% {
left: 0%;
}
40%,
60% {
left: calc(100% + 4px);
}
100% {
left: 0%;
}
}
<div class="container">
<span class="text first-text">Hi! I am </span>
<span class="text second-text" id="second-text">Freelancer</span>
</div>
2
Answers
You have taken the CSS variables approach which is sensible
I just don’t think you have written the result in the Javascript in a way that CSS will correctly receive. Here is what I suggest.
CSS
You can use
var(--steps)
, as you already have doneJavascript
You could put an inline style on the element to set the value of a CSS custom property and then reference that in your CSS, e.g.
Here’s a demo that cycles through a set of background colors as you click the element. The javascript updates an inline style to set the CSS
--color
property: