In this post, we explore an exciting combination of JavaScript and CSS to create an eye-catching text animation. By dynamically generating <h3> elements for each letter of a given string, we bring your text to life! The code snippet showcases a mesmerizing transformation and gradient background effect that activates upon hovering over the individual letters. Through the seamless integration of JavaScript’s createElement() function and CSS transitions, your web page will exude elegance and interactivity. Let’s dive on how to create amazing text animation using CSS, JS and HTML.
Create the text animation
<body> <div id="container"> </div> </body>
var myString = "Coding Beast"; for (var i = 0; i < myString.length; i++) { var letter = myString[i]; // Create a new div element var div = document.createElement("h3"); // Set the content of the div to the current letter div.textContent = letter; // Add class div.classList.add("letter") // Append the div to the container element var container = document.getElementById("container"); container.appendChild(div); }
This is what HTML code creates the script from above.
body{ background: black; } #container { display: flex; align-items: center; justify-content: center; } .letter { transition: 0.4s; transform: translateX(0); /* cursor: grab; */ color: red; } .letter:hover { transform: translatey(-1rem); background: -webkit-linear-gradient(120deg, hsl(19, 90%, 52%), hsl(65, 100%, 50%)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
The main purpose of this code is to dynamically create a series of <h3> elements within a <div> container, with each element representing a letter from the string “Coding Beast” or whatever string you will type.
The JavaScript code uses a for loop to iterate over each character in the myString variable. For each character, it creates a new <h3> element using document.createElement(“h3”). The content of the <h3> element is set to the current letter using the textContent property. It then adds the class “letter” to the <h3> element using the classList.add() method.
The newly created <h3> element is appended to the <div> container element, retrieved using document.getElementById(“container”). This results in a series of <h3> elements being added as children of the <div>.
The CSS styles defined in the provided CSS code are responsible for the visual appearance and effects of the <h3> elements. The background of the <body> is set to black, the <div> container is centered both vertically and horizontally using flexbox, and the .letter class defines transitions, transformations, and hover effects for the <h3> elements.
Overall, the code generates a visually appealing effect where each letter in the string “Coding Beast” appears as a separate <h3> element within a centered container, and hovering over the letters triggers a transformation and gradient background effect.
0 Comments