seb
seb's angle

Follow

seb's angle

Follow

How to make a scrolling text effect with CSS and JavaScript

seb's photo
seb
·Feb 7, 2023·

1 min read

How to make a scrolling text effect with CSS and JavaScript

I added this effect to my website and here's how I did it

the HTML is really simple

<div class="scrolling">
    <p>i like</p>
    <p id="element">CSS</p>
</div>

and for the CSS part, we have this

@keyframes scroll {
    0% {
        transform: translateY(100%);
        opacity: 0;
    }

    20% {
        transform: translateY(0px);
        opacity: 1;
    }

    80% {
        transform: translateY(0px);
        opacity: 1;
    }

    100% {
        transform: translateY(-100%);
        opacity: 0;
    }
}

.scrolling {
  margin-top: 20px;
  display: flex;
  gap: 4px;
}

#element {
  width: 30px;
  animation: scroll 4s ease-in-out infinite;
}

#element span {
  font-size: 14px;
  color: black;
  padding: 2px;
  border-radius: 3px;
}

this will create the text part that is supposed to scroll to an infinite loop without changing its value. We're gonna make the text change using JavaScript

const element = document.getElementById("element");
const words = [
    "JavaScript",
    "TypeScript",
    "Python",
    "HTML",
    "SQL",
    "CSS",
    "Svelte",
    "React",
];

let currentWord = 0;

element.addEventListener(
    "animationiteration",
    () => {
        currentWord++;
        if (currentWord === words.length) currentWord = 0;
        element.innerHTML = words[currentWord];
    },
    false
);

you should end up with something like this

you can now customize it using CSS however you want.

Here is a repl with the code

 
Share this