This JavaScript code snippet helps you to change text automatically on a web page. It cycles through phrases. JavaScript manages the text rotation, activating one text at a time. This feature is helpful for showcasing dynamic messages or announcements without manual intervention.
You can use this code on your website to grab visitors’ attention by changing text content automatically. It’s ideal for showcasing key messages, promotions, or quotes in a visually engaging manner.
How to Create Change Text Automatically JavaScript
1. First, create an HTML structure with a container element and multiple <p>
elements for your text. Add the class “is-visible” to the initial text you want to display.
<div class="container"> <p class="is-visible">YOU</p> <p>ARE</p> <p>AWESOME!</p> </div>
2. Define the styles for your container and text using CSS. Make sure the container is centered and styled to your preference. You can customize fonts, colors, and animations to match your website’s design.
body { margin: 0; padding: 0; -webkit-font-smoothing: antialiased; } .container { width: 100%; height: 100vh; display: flex; align-items: center; justify-content: center; background: #ee0979; background: linear-gradient(to left, #ee0979, #ff6a00); } .container p { font-size: 100px; font-family: "montserrat"; letter-spacing: 8px; text-indent: -8px; text-transform: uppercase; position: absolute; opacity: 0; visibility: hidden; transition: 0.4s all ease-out; font-weight: bold; color: white; } .container p.is-visible { opacity: 1; visibility: visible; }
3. Finally, let’s implement the JavaScript code. This code controls the automatic text changes. Copy and paste this code into your JavaScript file or script tag in your HTML document.
let texts = Array.from(document.querySelectorAll('.container p')); let i = 1; // starting from 1 because 0 already has is-visible, it would cause slight delay otherwise. setInterval(() => { texts.forEach(text => { text.classList.remove('is-visible'); }); texts[i].classList.add('is-visible'); i += 1; if (i >= texts.length) { i = 0; } }, 2000); //
That’s all! hopefully, you have successfully created a feature to change text automatically on your website. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.