skip to Main Content

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


  1. 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 done

    Javascript

    document.documentElement.style.setProperty('--steps', 8000);
    
    Login or Signup to reply.
  2. 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.

    <div style="--color: red"> ... </div>
    
    .someSelector {
       background: var(--color); /* red */
    }
    

    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:

    const colors = ['red', 'blue', 'green'];
    const demo = document.getElementById('demo');
    
    let colorIndex = 0;
    function nextColor() {
      colorIndex = (colorIndex + 1) % colors.length;
      demo.style = `--color: ${colors[colorIndex]}`;
    }
    
    demo.addEventListener('click', nextColor);
    #demo {
      background: var(--color, skyblue);
      padding: 2rem;
    }
    <div id="demo">click me</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search