setTimeout in CSS animation causing issues

I recently created an animation using CSS3.

The source code is quite simple. It involves displaying text and then making it disappear after 4 seconds.

Below you can find the current source code:

const intro1 = document.getElementsByClassName('intro1')[0];

setTimeout(() => {
  intro1.classList.remove('fade-in');
  intro1.classList.add('fade-out');
}, 3500);
body {
  margin: 30px 0;
  padding: 0 15px;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: aliceblue;
  width: 100%;
  height: 100%;
  font-size: 2rem;
  font-weight: 100;
}

span {
  text-align: center;
  position: absolute;
}

/* Intro animation */

.fade-in {
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  animation: fadeIn 4s;
}

.fade-out {
  animation: fadeOut 1s;
}

@keyframes fadeIn {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

@keyframes fadeOut {
  to {
    opacity: 0;
  }
}

I have defined the classes fade-in and fade-out, and initially set the classname of .intro1 to 'fade-in'.

With a delay of 3.5 seconds using setTimeout, I remove the class fade-in and add the class fade-out to make the text disappear.

The text appears and disappears as expected when I test it.

However, after the text disappears, it reappears unexpectedly.

https://i.sstatic.net/neRQQ.gif

I would like to prevent the text from showing again after its opacity becomes 0.

Could you suggest a solution for this issue?

Thank you.

Answer №1

Make sure to include the fade-out class in your code

.fade-out {
  animation: fadeOut 1s;
  animation-fill-mode: forwards; // don't forget this part
}

What is animation-fill-mode all about?

The animation-fill-mode property determines how the target element should be styled when the animation is not playing (such as before it starts or after it ends).

Possible values for the animation-fill-mode property include:

none - Default option. No styles are applied to the element before or after the animation takes place

forwards - The element maintains the style values set by the last keyframe (taking into account animation-direction and animation-iteration-count)

backwards - The element adopts the style values from the first keyframe (considering animation-direction), keeping them during any animation-delay period

both - Combines rules from both forwards and backwards, extending the animation properties in both directions

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

Crafting numerous CSS templates

I am currently working on creating multiple boxes or templates (5 on each row) from a movie API. I have successfully retrieved all the necessary data and do not require a responsive design. https://i.sstatic.net/CNz9R.png The issue arises when I attempt ...

What is the method for applying the action (hide) to every table cell that doesn't include a specific string in its ID?

I have a table with cells containing unique IDs such as "2012-01-01_841241" that include a date and a number. My goal is to filter the table to only display three specific numbers by sending a request and receiving those numbers. Is there a more efficien ...

Detecting changes in AngularJs elements

Below is the code snippet provided: handleFileSelect = (evt) -> console.log(1) file = evt.currentTarget.files[0] reader = new FileReader() reader.onload = (evt) -> $scope.$apply ($scope) -> $scope.myImage = evt.tar ...

Does text disappear when hovered over in CSS?

Having some trouble getting a text to display on hover over the parent container while adjusting the opacity. Despite trying multiple methods, it just won't show up no matter what I do! Here is my current code: .project{ position: relative; ...

What is the best way to combine and merge JSON objects that consist of multiple sub-objects?

I am working with a JSON response that contains multiple objects consisting of two main objects - datacenter and environment: "deployments": [ { "datacenter": { "title": "euw1", ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Error in Node.js: Trying to access the 'body' property of an undefined variable

While working on a project for a Udacity course, I encountered a stumbling block. The issue revolves around capturing user input from a form and making a post request to return a javascript object. However, when attempting to run the server with node js, I ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

When querying parameters within a URL, you may encounter JavaScript (Node) errors

My current setup involves using Firebase Cloud Functions, but I have run into an issue. Whenever a parameter with a # symbol is received, it does not get recognized. For instance: http://example.net?id=123#456. When I check the logged id, only 123 is disp ...

Avoid loading the background image by utilizing CSS to set the background image

Whenever I attempt to assign a background image using CSS, it triggers a console error. This is my CSS code: body { background-image: url("background.png"); background-repeat: no-repeat; } The error message displayed is: GET http://localhost/myWeb/ ...

Tips for securely storing visitor-entered form data on our computer from our webpage

Is there a way to store the information filled out by visitors on our website? <ul class="form"> <li class="short"> <label>First Name<span class="required"></span></ ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

Is it possible to locate and eliminate the apostrophe along with the preceding letter?

My objective is to tidy up a character string by removing elements that are not essential for the user and SEO, specifically the (letter before the apostrophes) in this case. I am looking for a regex solution or explanation of how to achieve this in PHP, a ...

Refreshing a DataTable by recreating it with a VueJS-populated HTML table

I am retrieving data from a database using Ajax and presenting it in an HTML table with the help of VueJS. Users can add, edit, and delete rows without any issues. However, I face a challenge when trying to incorporate a DataTable to provide users with th ...

Tips for effectively utilizing npm-check

Recently, I've been delving into the world of node.js and experimenting with the Spotify API to enhance my knowledge. After starting off with some example source code provided by Spotify, I now feel ready to create something unique on my own. With a ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...