Animate the text before it fades away

Could someone help me figure out how to make my text animations work correctly? I want to show and hide specific text with animation when buttons are pressed, but I'm having trouble implementing the hiding animation. Any guidance would be appreciated.

I apologize for any language errors as I used Google Translate to write this message.

Here is the code I have so far:

function hide(Id) {
  document.getElementById(Id).style.display = "none";
}

function show(Id) {
  document.getElementById(Id).style.display = "block";
}
p {text-align: center;
}
@keyframes text-fade-in {
  0% {
    opacity: 0;
    transform: translateX(-10vw);
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 1;
    transform: translateX(0vw);
  }
}

.text-fade-in {
  opacity: 0;
  animation-name: text-fade-in;
  animation-delay: 0.4s;
  animation-duration: 0.4s;
  animation-timing-function: easeOutCirc;
  animation-fill-mode: forwards;
}

@keyframes text-fade-out {
  0% {
    opacity: 1;
    transform: translateX(0vw);
  }
  80% {
    opacity: 0;
  }
  100% {
    opacity: 0;
    transform: translateX(-10vw);
  }
}

.text-fade-out {
  opacity: 1;
  animation-name: text-fade-out;
  animation-delay: 0.4s;
  animation-duration: 0.4s;
  animation-timing-function: easeOutCirc;
  animation-fill-mode: forwards;
}
<button onclick="show('Text1'); hide('Text2'); hide('Text3')">Text1</button>

<button onclick="show('Text2'); hide('Text1'); hide('Text3')">Text2</button>

<button onclick="show('Text3'); hide('Text1'); hide('Text2')">Text3</button>

<button onclick="hide('Text1'); hide('Text2'); hide('Text3')">Hide </button>

<p class="text-fade-in" id="Text1" style="display:none">Text1</p>

<p class="text-fade-in" id="Text2" style="display:none">Text2</p>

<p class="text-fade-in" id="Text3" style="display:none">Text3</p>

Answer №1

It seems that there's a limitation in animating the display property. While you have CSS opacity set, changing display to none in the onclick event would cancel that out.

I took the liberty of tweaking your code to include some transitions that align with what I believe you're aiming for.

const mainButtons = document.querySelectorAll('.btn')
const text1 = document.querySelector('#Text1')
const text2 = document.querySelector('#Text2')
const text3 = document.querySelector('#Text3')
const hideAll = document.querySelector('.hide-all')
const allText = document.querySelectorAll('p')

mainButtons.forEach((button, index) => {
  button.addEventListener("click", () => {
    switch(index) {
      case 0:
        text1.style.left = "0"
        break;
      case 1:
        text2.style.left = "0"
        break;
      case 2:
        text3.style.left = "0"
    }
  })
})

hideAll.addEventListener('click', () => {
  allText.forEach((text) => {
    text.style.left = "-100%";
  })
})
.text-container {
  position: relative;
}

#Text1 {
  position: relative;
  left: -100%;
  transition: all 500ms ease-in-out;
}

#Text2 {
  position: relative;
  left: -100%;
  transition: all 500ms ease-in-out;
}

#Text3 {
  position: relative;
  left: -100%;
  transition: all 500ms ease-in-out;
}
<button class='btn'>Text1</button>
<button class='btn'>Text2</button>
<button class='btn'>Text3</button>
<button class='hide-all'>Hide all</button>

<div class="text-container">
  <p class="text-fade-in" id = "Text1">Text1</p>
  <p class="text-fade-in" id = "Text2">Text2</p>
  <p class="text-fade-in" id = "Text3">Text3</p>
</div>
          

Answer №2

Could you be referencing this specific feature?

Take a look and let me know your opinion

I have also included a codepen link

let p = document.querySelectorAll("p");


for (let i = 0; i < p.length; i++) {
  p[i].addEventListener("animationend", function () {
    if (
      p[i].style.display !== "none" &&
      [...p[i].classList].includes("text-fade-out")
    ) {
      p[i].style.display = "none";
    }
  });
}

let isClearTimeout = false;
 function show(Id) {
  let ce = document.getElementById(Id);
  let ad = 0;
  if(ce.style.display !== 'none') return;

 
  Array.from(p).forEach((el) => {
    if (el.style.display !== "none") {
      hide();
      ad = parseFloat(window.getComputedStyle(el).animationDuration) * 1000;
    }
  });
  if(isClearTimeout){
    clearTimeout(isClearTimeout)
  }
  isClearTimeout = setTimeout(() => {
    if (ce.style.display === "none") {
      ce.classList.remove("text-fade-out");
      ce.style.display = "block";
      ce.classList.add("text-fade-in");
    }
  }, ad);
}

function hide() {
  // let ce = document.getElementById(Id);
  
  
  Array.from(p).forEach((ce)=>{
    if (ce.style.display === "block") {
    ce.classList.remove("text-fade-in");

    ce.classList.add("text-fade-out");
  }
  })
}
 @keyframes text-fade-in {
      0% {
        opacity: 0;
        transform: translateX(-10vw);
      }
      80% {
        opacity: 1;
      }
      100% {
        opacity: 1;
        transform: translateX(0vw);
      }
    }
    .text-fade-in {
      opacity: 0;
      animation-name: text-fade-in;
/*       animation-delay: 0.4s; */
      animation-duration: 0.4s;
      animation-timing-function: easeOutCirc;
      animation-fill-mode: forwards;
    }
    
    @keyframes text-fade-out {
      0% {
        opacity: 1;
        transform: translateX(0vw);
      }
      80% {
        opacity: 0;
      }
      100% {
        opacity: 0;
        transform: translateX(-10vw);
      }
    }
    .text-fade-out {
      opacity: 1;
      animation-name: text-fade-out;
/*       animation-delay: 0.4s; */
      animation-duration: 0.4s;
      animation-timing-function: easeOutCirc;
      animation-fill-mode: forwards;
    }
<body>
  <button onclick="show('Text1')">Text1</button>
  <button onclick="show('Text2')">Text2</button>
  <button onclick="show('Text3')">Text3</button>
  <button onclick="hide()">Hide all</button>

  <p class="text-fade-in" id="Text1" style="display:none" >Text1</p>
  <p class="text-fade-in" id="Text2" style="display:none" >Text2</p>
  <p class="text-fade-in" id="Text3" style="display:none" >Text3</p>
</body>

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

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Enhancing the styling of checkboxes using CSS and Javascript

My Javascript skills have been put to the test with a simple code snippet that customizes checkboxes by hiding them and using background images in CSS to display checks and unchecks. It's a neat trick, but I'm wondering if it's HTML/CSS comp ...

Unable to determine the size of the array being passed as a parameter in the function

When passing an array as a parameter to a function, I aim to retrieve its length. Within my code, I am working with an array of objects. groupList:group[]=[]; Within the selectItem function, I invoke the testExistinginArray function. selectItem (event) ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Update the appearance of buttons using AngularJS

I am trying to change the style of 3 buttons when they are clicked. I am not sure if angular has built-in functions like ng-class or ng-click that can help me achieve this. I have tried implementing them but it doesn't seem to work. <button class= ...

The functionality of the Wordpress editor is impaired when the parent element is set to display:none during rendering

My goal is to create a popup window with text fields and a wp_editor. The content is already rendered in the footer but only set to display none. I have made attempts at implementing this, however, they are not working perfectly. Each approach has its own ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...

Shifting the placement of a component in Vue JS when hovering the mouse

I am facing an issue regarding the positioning of components. I have four images, and when you hover over them, a specific component is displayed as shown below: https://i.sstatic.net/gybcy.png For example, hovering over a yellow image will display a dif ...

Issue with php's mysql_fetch_assoc() function

Seeking to fetch data from a function that holds my query. The retrieved data is sent back to the main page for printing using a while loop but encountering an error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given ...

Ensure that the flex item spans the entire width of the page

I'm struggling to make my audio-player resize properly to fit the full width of my page. I can't seem to figure out what I'm missing or doing wrong... (Current Look) https://i.sstatic.net/tEtqA.png I'm attempting to utilize HTML cust ...

Hover effects in CSS animations can be hit or miss, with some working smoothly while others may

Below is the HTML content: <div class="wrapper"> <figure align="center"><img src="http://www.felipegrin.com/port/or-site.jpg" alt=""><br><span>RESPONSIVE HTML5 WEBSITE FOR <br> OR LEDS COMPANY</span></fig ...

How can I convert the stylesheet link from fonts.google.com into a CSS class and include it in my file.css as an internal style instead of an external one?

Looking to incorporate a font from fonts.google.com? Here's how you can do it: <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300 ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

Creating line breaks for ToolTip titles in Material-UI can be achieved by using the appropriate syntax and

I am currently working with the ToolTip component and I have a query regarding displaying two lines for the title text - one line for each language rather than having them displayed on a single line. Is it possible to achieve this and how can I style the c ...

"div p" or "div * p"? Do they have the same meaning or is there a difference between them?

My knowledge of the "grandchild" selector in CSS was limited until I came across this insightful article. Intrigued, I decided to experiment with it and found that it resembles the universal selector (which targets all elements). Let's take a look at ...

What is the best way to display grouped items horizontally in an ASP.NET ListView?

My ASP ListView currently displays items vertically in columns with GroupItemCount set to 3: A D G B E H C F I Is there a way to adjust the display so that it groups items horizontally in rows like this? A B C D E F G H I This is the ListVi ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

Combining Multiple Tables Using Knex SQL Joins and Storing the Result in an Array

At the moment, I'm utilizing Knex to carry out queries on a MSSQL database. In my schema, there is a table named "Meals" which has the following columns: Id Additionally, there is also a table named "Vegetables" with the following columns: Id Meal ...