Text gently appearing and disappearing within a block

I’m looking to create a smooth fade effect for the content inside a block that is being dynamically changed by script. Instead of an instant change, I want the old content to fade out and the new content to fade in gradually without using jQuery — just pure JS and CSS. Here’s what I’ve tried: I defined two classes in CSS, one with transparency and one without, each with a transition set to 2 seconds. My plan was to toggle these classes when the content changes, expecting a smooth fade-out and fade-in effect. However, the content simply changes instantly. CSS:

.non-opaque {
    opacity:0;
    transition: opacity 2s linear;
}
.opaque {
    opacity:1;
    transition: opacity 2s linear;
}

HTML

       <div class="alert alert-info" id="wrapper">
            <p id="text-box">…</p>
        </div>

JS

var textBox = document.getElementById('text-box');
window.onload = function () {
    var failCounter = 0;
    var current = notes[Math.floor(Math.random() * 12)];
    textBox.className = 'opaque';
    textBox.innerHTML = '…';
    function keyClicked(event) {
        if (event.target.className.split(' ')[1] === current) {
            textBox.className = 'non-opaque';
            textBox.innerHTML = '*some altered content*';
            textBox.className = 'opaque';
    …

In my JavaScript code, I initially set the content wrapper block to the 'opaque' class with the initial content. Then, under certain conditions, I switch it to 'non-opaque', update the innerHTML with the relevant content, and finally revert back to 'opaque'. Despite this approach, no animation takes place. What am I doing wrong?

Answer №1

One issue you may be facing is toggling the opacity too quickly, interrupting the initial transition process.

To solve this problem, consider delaying the change in innerHTML and resetting of the opacity until after the transition has finished.

Below is a concise demonstration using a looping example that highlights the importance of incorporating a setTimeout function.

var p=document.getElementById("change"),text=["One","Two","Three","Four","Five"],x=0,interval=setInterval(function(){
    x++;if(x===text.length)x=0;
    p.classList.add("hide");
    setTimeout(function(){
        p.innerHTML=text[x];
        p.classList.remove("hide");
    },500);
},2000);
#change{
    color:#000;
    font-family:arial;
    padding:5px;
    transition:opacity .5s linear;
}
.hide{
    opacity:0;
}
<p id="change">One</p>

Answer №2

The browser doesn't wait for transitions to finish before reverting the class back to opaque.

This effective fiddle separates the transition into its own selector and utilizes a transitionend event listener to ensure the element completely fades out before altering the content and fading it back in.

http://jsfiddle.net/0m3Lpwxo/1/

CSS:

.opaque {
    opacity: 1;
}

.non-opaque {
    opacity: 0;
}

#test {
    transition: opacity 1s linear;
}

HTML:

<div id="test" class="non-opaque">this is content</div>
<button onclick="toggle()">toggle</button>

JavaScript:

function transitionEnded() {
    var el = document.getElementById('test');
    el.innerHTML = "hello.";
    el.classList.remove('non-opaque');
}

function toggle() {
    var el = document.getElementById('test');
    el.addEventListener("transitionend", transitionEnded, true);
    el.classList.add('non-opaque');
}

Answer №3

To enhance your design, consider incorporating browser-specific styles in addition to your current definition. For example, you can use -webkit-transition: opacity 2s linear; for WebKit browsers.

Instead of redundantly adding transitions to multiple classes, focus on a consistent feature of your element that won't change, such as its ID, and define the transition style rules there. This approach will help streamline your CSS code and keep it more maintainable.

For comprehensive guidance on working with CSS transitions, I recommend consulting this valuable resource: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Answer №4

Give this a shot:

<div id="elementFade">Your Text Here</div>

function fadeOutText(id,val){
  if(isNaN(val)){ val = 9;}
  document.getElementById(id).style.opacity='0.'+val;
  //For Internet Explorer
  document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
  if(val>0){
    val--;
    setTimeout('fadeOutText("'+id+'",'+val+')',90);
  }else{return;}
}

function fadeInText(id,val){
  if(isNaN(val)){ val = 0;}
  document.getElementById(id).style.opacity='0.'+val;
  //For Internet Explorer
  document.getElementById(id).style.filter='alpha(opacity='+val+'0)';

  if(val<9){
    val++;
    setTimeout('fadeInText("'+id+'",'+val+')',90);
   }else{return;}
}

Source: Here.

Answer №5

The JavaScript code I have utilized is as follows:

function update(){
    var element = document.getElementById("box");
    element.className = element.className + " transparent";
    setTimeout(function(){
       element.className = "opaque";
        element.innerHTML = "UPDATED";
    },1000);
}

Take a look at this DEMO, which includes the necessary CSS:

.opaque {
    opacity:1;
    transition: opacity 1s linear;
}
.transparent {
    opacity:0;/* No need to include transition property here */
}

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 is preventing the question div and buttons from expanding according to their content?

After experimenting with setting the height of the question div to auto, I found that it would stretch to fit its content. However, I am looking for a solution without overflow: auto or scroll. Is there a limit to how responsive it can be once a certain ...

Determine whether a value is present in a JavaScript object in real-time while typing in a TextBox with the help of angular

Within a textbox, users have the freedom to input any value. Upon each keystroke, I must validate whether that value already exists in $scope.arrayObject. A common approach involves attaching a key-up event handler to the textbox and performing the necessa ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

If the browser fails to fetch a page or a link is unresponsive when navigating to the current page

When a link in the Browser, either does not fetch a page or the link is not working when pointing to the current page, it can be frustrating. I encountered this issue with a link in a menu while working on a project. Specifically, when a user is on the Get ...

Move the last specified elements to the beginning of the array

I have an array let colorsArr = ["red", "green", "purple", "pink", "black"]; Is there a way to retrieve a specific number of elements from the END and move them to the BEGINNING of the array? Desired result: example 1: //move last 3 elements let expec ...

Disabling the click functionality using ng-disabled on an anchor tag is effective, but the tag remains

I'm facing an issue with an anchor tag that I've styled as a download button using Bootstrap's CSS. The problem is even though I have the ng-disabled attribute in the tag, which visually disables the button, it can still be clicked. Here&apo ...

What is the best way to display an international phone number using Angular Material V6?

I've been working on a project that utilizes Angular Material V6. My goal is to display international phone numbers with flags in a Material component text box. After some research online, I came across an npm module that achieved this but it was tail ...

Hover background color not being applied to child elements within Button element in Firefox

Ensuring that my product is SEO-friendly, I incorporated semantic markup using the button element and schema attributes. To separate individual items, I utilized "span" elements while setting hover effects on selected items by adding display:block. This a ...

Tips on choosing the initial TD elements within a row

Is it possible to create a CSS code that changes the color of the first TD element in each TR row within a table with the class mytable, recursively? Can you provide an example of how this CSS would look? <table class="mytable"> <tr ...

Is Angular UI's data binding more of a push or pull mechanism? How can I optimize its speed?

Suppose I have a variable a that is displayed in HTML as {{a}}. If I then update its value in TypeScript using a = "new value";, how quickly will the new value be reflected in the user interface? Is there a mechanism that periodically checks all bound var ...

What is the best way to alter the text of a button when the mouse hovers over it?

I'm looking to create a button that can dynamically change the text inside it when the cursor hovers over it, and then revert back to the original text when the cursor moves away from it. I attempted this in VScode using "document.getElementById().inn ...

Combine both typescript and javascript files within a single Angular project

Is it feasible to include both TypeScript and JavaScript files within the same Angular project? I am working on a significant Angular project and considering migrating it to TypeScript without having to rename all files to .ts and address any resulting er ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

What causes errors in URL routeProvider with AngularJS?

Implementing routeProvider in Angular JS allows me to structure my links like this: www.site.com/profile#/profile/profession/3 However, when trying to access the page, Angular JS displays the following error message: Uncaught Error: Syntax error, unreco ...

jquery deleting the parent container of a child element

I have been attempting to eliminate the parent element of the label associated with the attribute record_type. Below is the HTML content: <div id="append"> <div class="col-md-6 form-group hide_fields" style="display: block;"> <l ...

What is the process for identifying the ActiveX control being referenced on a webpage?

After developing a web application using ASP.NET Web Forms, I encountered a challenge with a client who has strict security policies. Whenever they try to access the web page, Internet Explorer displays a message stating: Your security settings do not all ...

Delivering an XML file generated by PHP to a JavaScript parser

I'm in the process of creating a smart TV app that streams live content. The app functions properly when I provide it with a valid XML playlist. However, when I attempt to use PHP to generate the XML file (which generates without any issues), it fail ...

Django is giving an error message, indicating an invalid block tag. It is looking for either 'empty' or 'endfor' instead of 'else'. This may be due to not registering or loading the tag properly

I'm having some trouble getting this to load correctly. I'm still learning Python and working on understanding its formatting. I've gone through previous inquiries where there seemed to be a syntax error, but I can't seem to pinpoint an ...

Learn how to calculate and showcase time discrepancies in minutes using Angular2

I am currently working on an Angular app that displays orders using the *ngFor directive. Each order has a datetime field indicating the date it was created. My goal is to implement a timer that shows how long a customer has been waiting for their order ...

Incorporate a background image and overlay it with CSS animations for a dynamic effect

I have set up a fiddle, but it seems like the display is not quite right. You can check it out here - http://jsfiddle.net/kVNQb/ - although it might be helpful to take a look at the code regardless. The snow animation I am using is from this website: My ...