Leveraging JavaScript to incorporate smooth transitions like fade in and fade out during text changes

Below is my JavaScript code that switches between 2 words every 2.5 seconds. I want to enhance the transition between the words by adding a fading effect using jQuery. How can I integrate this into the recursive function? Any suggestions?

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}
.banner-right h2 {
  font-size: 50px;
  font-weight: 300;
  color: #ffffff;
  margin: 15px 0 45px 0;
}
<h2 id="changeText">Data Scientist</h2>

Answer №1

If you're working with Vanilla JavaScript, an effective approach would be utilizing CSS transitions and the classList property.

Here's an example implementation:

CSS

#updateText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}

JavaScript

function updateContent() {
    element.classList.add('hide');
    setTimeout(function () {
        element.innerHTML = content[counter];
        element.classList.remove('hide');
        counter++;
        if (counter >= content.length) {
            counter = 0;
        }
    }, 500);
}

Live Example:

var content = ["first", "second"];
var counter = 0;
var element = document.getElementById("updateText");
setInterval(updateContent, 2500);

function updateContent() {
    element.classList.add('hide');
    setTimeout(function () {
        element.innerHTML = content[counter];
        element.classList.remove('hide');
        counter++;
        if (counter >= content.length) {
            counter = 0;
        }
    }, 500);
}
#updateText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}
<h2 id="updateText">Web Developer</h2>

Please note: The use of !important in the CSS is necessary here as opacity: 1; with an ID selector takes precedence over a class selector.

Answer №2

Switch out the following:

elem.textContent = text[counter];

For:

$(elem)
    .fadeOut(400)
    .html(text[counter])
    .delay(400)
    .fadeIn(400);

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

Overriding makeStyles CSS in Material UI Styling

When creating classes using makeStyles and useClasses, I've noticed that MUI CSS tends to take precedence over my custom styles unless I use the '!important' rule. Is there a way to override MUI styles without having to rely on '!import ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Bring in d3 from unpkg

Uncertain of which file to import, I am seeking guidance on how to import d3 from unpkg.com. Can someone advise me on the equivalent unpkg version of: import * as d3 from "d3"; ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

Specific phrase enclosed within div element

How can I concatenate three strings together when one of them is enclosed within a strong tag? The result is not what I expected. Can you identify the issue here? Result: There is no Colors for <strong>blah</strong> in the database. Expecte ...

Having trouble retrieving the second parent of my input element using jQuery

Within my web application, there exists a particular input element. I am aiming to alter the text within the span below from "-" to a different value. Here is the current markup: <span dir="none"> <table id="OrderQuickOrder_a91a0ce2-7fb6-4c9 ...

Establishing Routing for Angular within an ASP.NET Web API 2 application

Currently, I am facing difficulties in setting up the routing for my project. There are several cases that need to be handled, but I am struggling to make them work as intended. case 1: / - Should route to the index of the angular app Case 2: /{angular ...

Padding has an impact on the widths of flexbox items

Take a look at this code snippet: http://jsfiddle.net/56qwuz6o/3/ <div style="display:flex"> <div id="a">a</div> <div id="b">b</div> <div id="c">c</div> </div> div div { ...

Difficulty comprehending the fallback for JSON.parse in jQuery.parseJSON

Check out the origin of $.parseJSON function (data) { if (typeof data !== "string" || !data) { return null; } // Remove leading/trailing whitespace for compatibility data = jQuery.trim(data); // Try native JSON parser first ...

Oops! There was an unexpected error: TypeError - It seems that the property 'title' cannot be read because it is undefined

HTML document example <ion-header> <ion-toolbar color="danger"> <ion-buttons> <button ion-button navPop icon-only> <ion-icon ios="ios-arrow-back" md="md-arrow-back"></ion-icon> </button> ...

Generating random numbers within specified character limits using Javascript and Selenium

Just starting to learn javascript - I am working on creating random user IDs for my selenium test scenarios. The line of code I am using for the value is as follows: javascript{Math.floor(Math.random()*11111)} However, there is a specific field that need ...

Accordion jQuery failing to display tabs

I have a question about using 2 jQuery accordions with tabs inside them. Everything seems to be working, but when I try to expand the second accordion, the two tabs inside don't render properly. I'm not sure what the issue is. Any help on this wo ...

Utilize discord.js to create commands with multiple arguments

I'm currently working on creating a command with multiple arguments, like this example: !Poll "This is the title" "This is the description" "This is the time" However, I've encountered an issue where it only recognizes the first 2 arguments. ht ...

Error: Encountered an unexpected token within the node_modules/aws-iot-device-sdk/thing/index.js file

I've integrated the aws-iot-device-sdk into our reactjs application. However, we encountered an error while trying to execute the command NODE_ENV=production npm run compile. The error message I received pertains to a syntax issue in the file paths me ...

Hey there, what exactly does 'TypeError: Cannot access the 'scopedFn' property of an undefined object' mean?

Having trouble implementing RadListView with Nativescript-Vue. I am attempting to utilize a v-template for the header followed by another v-template for the list itself. 1) The header does not seem to be recognized, as only the standard v-template is disp ...

Activate anchor classes in several anchor link menus simultaneously

I have a one-page website with multiple menus filled with anchor links. Here is an example of what they look like: <ul> <li><a href="#home" class="active" onclick="closeNav();">Home</a></li> <li><a href="#abo ...

Is there a faster alternative to using jQuery's indexOf method?

Looking to create a search box for a large set of options (around 2000 options) The indexOf method is very slow...any alternative solutions? Jquery Code : $('#textfortitlesearch').on('keyup', function() { var query = this.value ...

Unable to center text in a Bootstrap 4 div

Hello everyone, I have come across this code snippet: <div class="row mt-5" id="System Requirements"> <div class="col-4"> <h4 class="text-nowrap font-weight-bold pl-4">System Requirements</h4> </d ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

The Facebook like button disappears after being used just once

I've encountered an odd issue that hopefully someone can help me understand. WEBSITE: ISSUE: Initially, the like button functions properly. However, upon refreshing the page or navigating away and returning to the homepage, the like button mysterio ...