Is it possible to make text animation appear and fade after every click event in HTML, CSS, and JavaScript?

Currently, I have to press the button twice for the text to appear and fade. How can I make it so that clicking the button once will show and fade the "Added!" text every time, even if clicked while the text is fading?

I've attempted using CSS focus, rearranging JavaScript code, and adding a while loop, but have not been successful. Any guidance would be appreciated.

  function cartAdded() {
    var text = document.getElementById("added-notification");
    if (text.style.display === "none") {
      text.style.display = "block";
    } else {
      text.style.display = "none";
    }
  }
  .added-fade-out {
    opacity: 0;
    display: none;
    animation: fadeOut 1s ease-out;

  }

  @keyframes fadeOut {
    0% {
      opacity: 1;
      display: none;
    }

    50% {
      opacity: 0.5;
      display: block;
    }

    100% {
      opacity: 0;
      display: none;
    }
  }
  <button type='button' onclick="cartAdded()">Click me</button>
  <p id='added-notification' class="added-fade-out">Added!</p>

This was initially a question with unclear terminology, which led to searching for a more precise solution. The goal is to restart the animation after each click, rather than only at the end of the current animation. This aligns closely with what I am aiming to achieve (Animation should play every time you click the button)

To replay the animation after each click:

  function showMessage() {
    let message = document.getElementById('child');

    if (message.classList.contains('d-none')) {
      message.classList.remove('d-none');
    }

    // message.classList.add('d-none');
    message.style.animation = 'none';
    message.offsetHeight;
    message.style.animation = null;
  }
  .parent {
    position: relative;
    width: 600px;
    height: 150px;
  }

  @keyframes msgSuccess {

    50% {
      opacity: 1;
    }

    99% {
      opacity: 0;
    }

    100% {
      opacity: 0;
      display: none;
    }
  }

  .child {
    position: absolute;
    width: 100%;
    height: 50px;
    animation-name: msgSuccess;
    animation-duration: 1s;
    opacity: 0;
  }

  .d-none {
    display: none;
  }
  <button onclick="showMessage()">Click Me</button>
  <div id="parent" class="parent">
    <div id="child" class="child d-none">Message</div>
  </div>

Answer №1

To ensure that the text.style.display property does not return an empty string, it is essential to explicitly set the initial value to none.

var text = document.getElementById("added-notification");
text.addEventListener('animationend', () => {
  text.style.display = "none"
})

function cartAdded() {
  if (text.style.display === "none") {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
.added-fade-out {
  opacity: 0;
  display: none;
  animation: fadeOut 1s ease-out;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
  }
}
<button type='button' onclick="cartAdded()">Click me</button>
<p id='added-notification' class="added-fade-out" style="display: none">Added!</p>

Answer №2

Utilize the animationend event in order to eliminate the fade Out

const
  notificationButton = document.querySelector('#notification-btn')
, pNotificationText  = document.querySelector('#notification-text')
  ;

notificationButton.addEventListener('click', () =>
  {
  notificationButton.disabled = true;
  pNotificationText.classList.replace('noDisplay','show-fade-out')
  })
pNotificationText.addEventListener('animationend', () =>
  {
  notificationButton.disabled = false;
  pNotificationText.classList.replace('show-fade-out','noDisplay') 
  })
.noDisplay {
  display: none;
  }
.show-fade-out {
  animation: fadeOut 1s ease-out forwards;
  }
@keyframes fadeOut {
  100% { opacity: 0; }
  }
<button id="notification-btn">Click me</button>
<p id='notification-text' class="noDisplay" > Added! </p>

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

Is your iPhone struggling to display animation sprites correctly?

After testing on Android and iPhone, I found that the website works great on Android but lags on iPhone. I suspected that the issue might be related to image preloading, so I tried adding a simple jQuery preloader, but it didn't solve the problem. Th ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Product sketching libraries in JavaScript

Can somebody assist me in locating a suitable JS library that is capable of generating a product sketch similar to this one: Partition sketch? I am currently using Next.js, and I am encountering difficulties with most libraries due to Next.js utilizing SSR ...

After modifying the select option, the input field remains disabled

I successfully developed a self-contained code snippet that toggles the enable/disable state of input fields. It works flawlessly on my HTML page. Check it out below: Identification Type: <select name="Identification-Type" id="Identification-Type"& ...

Employ Jade as the template engine for your Angular 2 project

As I transition to developing MEAN apps with Angular2 instead of Angular1.x, I am encountering a challenge involving the use of jade/pug as my template engine in angular2. I came across a tutorial on how to implement this using webpack, but it seems to b ...

Encountering a problem when using the routingService to navigate inside a JavaScript function

Within my Angular component, I have a method called onCellPrepared. In this method, I am using jQuery to attach a span tag. I want to be able to trigger an Angular service to navigate to another page when the span tag is clicked. How can I successful ...

The consistent index is shared among all dynamically generated elements

I'm currently working on a project where I am generating dropdowns within a table dynamically. I am attempting to determine the index of the dropdown that triggered the event in the following way: $(".template").on('change', '.dataType ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

Looking to modify the color of the post's <h1> heading if there is no featured image assigned to it

While working on my WordPress blog and browsing various other WordPress blogs, I noticed that setting a featured image can really make a difference in grabbing the reader's attention. However, when a featured image is not set, I have a default backgro ...

Encountered an error while attempting to access property 'someProperty' of an undefined value in a React application

Currently, I am developing an application that involves passing variable values within a Navlink using state from one component to another. Once the values are received, they need to be loaded into input fields and then upon clicking the submit button in t ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

What steps can be taken to halt the execution of a command that includes the useState function

I've implemented code that sends a GET request to my backend (mySQL) to retrieve data and then uses useState to store the response.data. const baseURL = 'http://localhost:5000/api/user/timesheet/13009'; const [DataArray , setDataArray] = us ...

Implement a button transformation upon successful completion of a MySQLi update using AJAX

When displaying multiple database results with buttons that can be turned on or off inside a div, I am looking to implement AJAX to toggle the button state between ON and OFF upon clicking, and then update the button without refreshing or reloading the ent ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

ForEach fails to refresh the primary array

I am currently working on extending the values of each item in an array. My array consists of objects with x, y, and z fields. I aim to append more items to each object within the array using information obtained from a http.get call's response. The ...

"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be exe ...

Is the IE7 Modal Dialog Misaligned?

Update After some investigation, I discovered the root cause of the problem. In my code, I was referencing the height of the overlay, which resulted in different values in IE7 compared to other browsers. To resolve this issue, I adjusted the code to refe ...

Ways to identify when a modal window is being closed in the angular-ui $modal component

I am currently utilizing the $modal from angular-ui to generate a modal window. Below is the code snippet for creating the modal: this.show = function (customModalDefaults, customModalOptions, extraScopeVar) { //Create temporary objects to work with s ...

Where do JQuery and framesets vanish to?

Whenever I attempt to use the console to create an element with the tag frameset, it returns no result: $('<div id="content" data-something="hello" />') => [<div id=​"content" data-something=​"hello">​</div>​] $(&apo ...