Is it possible to loop an animation every time the text within the element is altered?

I have an issue with my HTML text element that triggers an animation on page load. I am attempting to write a script that changes the original text to a new one and replays the animation. Here is a snippet of my code:

setTimeout(function typewriter() {
    let txt;
    let themes = document.getElementById("themes");
    txt = "Games";
    themes.innerText = txt;
    themes.classList.add("changer");
}, 4000);
.typewriter h1 {
    color: #ffffff;
    background-color: #000000a8;
    border-radius: 5px;
    padding: 10px;
    font-family: monospace;
    font-size: 35px;
    overflow: hidden; /* Ensures the content is not revealed until the animation */
    border-right: .15em solid #333333; /* The typewriter cursor */
    white-space: nowrap; /* Keeps the content on a single line */
    margin: 0 auto; /* Gives that scrolling effect as the typing happens */
    animation: 
      typing 2s steps(30, end),
      blink-caret .5s step-end infinite;
}
.changer {
    animation: typing 2s steps(30, end), blink-caret .5s step-end infinite;
}
/* The typing effect */
@keyframes typing {
    from { width: 0 }
    to { width: 100% }
}
  
/* The typewriter cursor effect */
@keyframes blink-caret {
    from, to { border-color: transparent }
    50% { border-color: #333333 }
}
<div class="typewriter">
    <h1 id="themes">Science</h1>
</div>

I am facing a challenge where the animation does not restart after the text changes in 4 seconds. Can someone provide assistance on this issue? Appreciate your help. Thank you.

Answer №1

Firstly, instead of using setTimeout, it is recommended to use setInterval for repeating the function.

Secondly, if you wish to change the text to a specific value each time the function is called, consider storing the texts in an array first.

var texts = [];

//Initialize counter
var curr = 0;

//Add texts to array
texts.push("Games");
texts.push("Science");

setInterval(function() {
    let txt;
    //Assign value from texts array based on counter
    txt = texts[curr];
    let themes = document.getElementById("themes");
    themes.innerText = txt;
    themes.classList.add("changer");

    //Increment counter
    curr += 1;

    //Reset counter when it reaches end of array
    if(curr >= texts.length) curr = 0;
}, 4000);

Although the animation may not work in certain cases, this code is effective for changing the text every 4 seconds.

Feel free to include any number of texts that you prefer.

Answer №2

I managed to find a clever solution in JavaScript that dynamically increases the width of an element from 1% to 100%! Check out the code snippet below:

var items = [];

// Initialize a counter
var current = 0;

// Populate the array
items.push("Software");
items.push("Technology");

setInterval(function() {
    let itemText;
    // Retrieve the value from the array based on the current counter
    itemText = items[current];
    let categories = document.getElementById("categories");
    categories.innerText = itemText;

    var width = 0;
    var intervalId = setInterval(frame, 10);
    function frame(){
        if(width >= 100){
            clearInterval(intervalId);
        } else {
            width++;
            categories.style.width = width + "%";
        }
    }

    // Increment the counter
    current += 1;

    // Reset the counter if it reaches the end of the array
    if(current >= items.length) current = 0;
}, 4000);

Big thanks for your assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

What are some techniques for styling a label element with an empty for attribute using CSS?

Here is what I currently have: <label class="filter-label" for="pv[]181"> ::before white <span class="count">5</span> ::after </label> My goal is to modify the ::after element within that label, but so far my attempts ...

Issue encountered while attempting to compress tailwindcss

I attempted to reduce the size of my tailwindCSS by creating a script in my package.json: "tw:prod":"NODE_ENV=production npx tailwindcss-cli@latest build ./src/css/tailwind.css -o ./public/css/tailwind.css", However, I encountered the ...

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

Guide on how to position a single anchor at the center of a div alongside other elements

I am having trouble centering an anchor on my webpage. I have tried using text-align: center;, but it always puts the link on a new line due to the required div element. Other methods like margins and spans have not worked for me either. span.right { ...

ChartJS does not function properly when included in a .php file that is loaded using jQuery's .load() method (

I am facing an issue with this plugin not working when I use the jQuery ajax function .load(). Below is the snippet of my PHP code: <script src="../Chart.js"></script> <script type="text/javascript" src="../functions.js"></script> ...

How to efficiently use nested $.each() in DataTables with jQuery

After receiving Json data from the server, I utilize DataTables to display the information accordingly. The json contains multidimensional arrays with rows consisting of columns that may have more than one value. Here's an excerpt: { "info_table ...

The styling of Material UI's contained button is being overridden by MuiButtonBase-root

Currently, I am working with material-ui in a react project. In one of my components, I have incorporated a simple contained button: <Button variant='contained' color='primary'> Edit</Button> However, despite setting it as ...

Tips for transitioning from custom CSS to Material UI's CSS in JS

I came across a project where someone implemented components with custom CSS. One interesting thing I noticed was a wrapper component, similar to Material UI's Container or just a simple div with applied styles. export const Container = styled.div` ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Update the JSON data based on the specifications outlined in my project

class Transformation { constructor() { this.colHeaders = { error_description: "Description", error_status: "Status", error_code: "Error Code" }; } getColHeader() { return this.colHeaders; } } var jsonData = { error ...

Utilizing HTML5 Video Autoplay with AngularJS ng-show: A Comprehensive Guide

How can I implement a video using the HTML5 video tag with autoplay in an AngularJS web application? I attempted to use the following code: <video ng-show="condition" autoplay ng-src="{{video.src}}"></video> Upon loading the web application, ...

How to Get into a Nested Class in JavaScript

I'm struggling to articulate my question, but I know there's a solution out there. I have profile cards in HTML, each with the class "card" containing two numbers. My goal is to display a progress bar specific to the % relationship of these numbe ...

Invoke a server-side function with JavaScript or jQuery

Is it possible to call a server-side method using JavaScript or jQuery during a postback? I have a created an anchor button and I want it to function like a link button, triggering a postback and calling an event. I'm thinking that JavaScript might b ...

Having trouble implementing a cookie on the second domain using the first domain. Can't seem to get it to work properly

Currently, I am working on integrating ajax functionality with PHP. My main objective is to generate a cookie on the page where ajax call is made. The scenario involves two distinct domains - domain1.com and domain2.com. Essentially, the ajax code is imple ...

Mastering the Art of Tab Selection with Jquery

I am trying to implement a tabs control using jQuery. Here is the HTML code I have: <div id="tabs" class="news1"> <ul> <li><a href="#tabs-1">Track</a></li> <li><a href="#tabs-2">History&l ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

Managing User Sessions in Meteor

Is there a way to dynamically retrieve and set the pageTitle for my Meteor app using jQuery or any other method? I've attempted to achieve this by creating a session when a specific div class is present on the page, but it doesn't seem to be work ...

Mastering Excel Automation

Hello, I am looking to download an Excel sheet that contains a macro. However, I am using a PHP script to handle the download process. Is it feasible to download an Excel sheet with a macro in PHP? ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...