Gradually bringing a tag into view, gently fading it away, and then altering the text before beginning the cycle anew

I have a situation where an tag's content is being dynamically changed with jQuery and then faded in and out using the Velocity JS library along with the setInterval function. Initially, everything works smoothly for about 30 seconds. However, after that, there seems to be a malfunction where jQuery starts altering the contents of the tag before it has completely faded out.

Below is the JavaScript code:

let counter = 0;

function chooseWord() {
    let words = ["foo", "bar", "foo"];

    if (counter !== 2) {
        counter += 1;
    } else {
        counter = 0;
    }

    return words[counter];
}

function refreshText() {
    $("#div").text("Foo " + chooseWord())
        .velocity("fadeIn", {
            duration: 2500
        })
        .velocity("fadeOut", {
            delay: 1500,
            duration: 2500
        });
}

$(document).ready(function() {
    refreshText();

    setInterval(function() {
        refreshText();
    }, 7000);
});

Here is the corresponding tag being used:

<h1 class="foobar" id="div"></h1>

I've attempted to use jQuery's timer as well but encountered the same issue. Can anyone pinpoint what might be causing this problem or suggest an alternative approach to achieving the desired outcome?

Answer №1

To achieve the desired outcome, simply adjust the order of operations in your code. By placing the text-change command after the fade-out function, you ensure that the element fades out before jQuery updates its text content.

$("#div")
.velocity("fadeIn", {
  duration: 2500
})
.velocity("fadeOut", {
  delay: 1500,
  duration: 2500
})
.text("Foo " + chooseWord());

Here is the fiddle link for reference: https://jsfiddle.net/Nisarg0/gLed0h1y/

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

What could be the reason for the CSS stylesheet not functioning properly on mobile devices?

I am a newcomer to web development and currently working on a website for a massage therapist using bootstrap. However, I am facing an issue where my CSS styles are not displaying correctly on mobile devices. The backgrounds and bootstrap navbar disappear, ...

Align buttons in the center of a card or container using HTML and CSS

Hi everyone, this is my first time posting so please go easy on me. I've been struggling to align the buttons at the bottom of my cards to make them look neater. I've tried using flexbox but it doesn't seem to be working. Some people have su ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

What causes a div to shift to the right when the margin-left is set to auto?

I am curious to understand why setting the margin-left of the div with id="pink" to auto causes the div to move to the right side. Take a look at the image below: HTML <div id="aqua">aqua</div> <div id="yellow">yellow</div> & ...

Identify the CSS class for the ionic component on the webpage

Currently, I am in the process of developing an application using ionic 2 and angular 2. Within this app, I am utilizing the ionic 2 component known as ModalController. Unfortunately, I have encountered a challenge when attempting to adjust the size of th ...

Can Node.js fetch a PHP file using AJAX?

The Challenge: Greetings, I am facing an issue with my website that features a game created using node.js, gulp, and socket.io. The problem arises when I attempt to call a php file from node.js. While the file returns a success message (echo in the file) ...

Is it necessary to close the navigation drawer after selecting an item?

Currently, I'm working on a project for my University where I am trying to incorporate a feature that will automatically close the navigation drawer whenever any of its items are clicked. However, I am facing some challenges figuring out how to achiev ...

What is the most effective method for discerning the availability of fresh data?

Many highload websites are able to notify their users of new messages or topics in real-time without the need for page refreshing. How do they achieve this and what approaches are commonly used? There appear to be two main methods: Continuously querying ...

Troubleshooting issue with jQuery animate not correctly scrolling

I am experiencing an issue with my jQuery code that is supposed to scroll a smaller container element within a larger container element when a button is clicked. Despite testing with an alert and verifying that the code is working, the scrolling functional ...

What is the best way to transmit data via $router.push in Vue.js?

I am currently working on implementing an alert component for a CRUD application using Vue.js. My goal is to pass a message to another component once data has been successfully saved. I attempted to achieve this by passing the data through $router.push lik ...

`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property. Check out the fiddle here: https://jsfiddle.net/4hd2vrex/ The issue arises when users make multiple selections, leadi ...

Stylish dropdown menu design inspired by W3CSS website

I recently implemented a CSS dropdown menu example that I found on a website, but it's not working with my code. I double-checked for typos but couldn't find any. Even when I tried to directly copy the code and replace the content with my own, i ...

Tips for altering the color of spans that share a common top position without affecting the surrounding sibling elements above or below

Is there a way to change the color of spans with the same top position, excluding sibling elements above or below, in a paragraph made up of spans? I've been working on how to change the color of the line of span tags that contain another span with t ...

What is the reason behind the modification in flex item size when align-items property is applied?

When creating the responsive design, I utilized flexbox. Surprisingly, without changing the size of each flex-item, applying align-items:center caused the size of the first flex item (PICTURE 2) to change when displayed in a vertical view. On the other han ...

Incorporate titles for items in the jquery caroufredsel plugin

I am currently using the second example of the caroufredsel plugin, which can be found on this page . I am attempting to add a caption for each picture. To achieve this, I have used `li` and `lis` in my HTML code: <div class="list_carousel"> &l ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

Ensuring the Accuracy of POST Parameters Using Express-Validator

I've been working on adding parameter validation to my Node/Express API by utilizing express-validator. However, I encountered a situation where even though I sent a POST request with a missing "name" field using the curl command curl -X POST -d "foo= ...