The animation will only activate upon the initial click of the button

I'm looking to add a simple text animation to my website. The idea is that when a button is clicked, the text transitions from being fully transparent to fully visible, and then back to transparent. I've written some code to achieve this animation, but it only works the first time the button is clicked. After that, the animation stops working when the button is clicked again:

function animation() {
  $("span").removeClass("opacity-effect");
  $("span").addClass("opacity-effect");
}
span{
  opacity: 0;
}

.opacity-effect {
  animation-name: animate-opacity-effect;
  animation-duration: 1400ms;
  animation-fill-mode: forwards;
  opacity: 0;

}

@keyframes animate-opacity-effect {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Hello World!</span>
<button onClick="animation()">
   Start animation
</button>

Answer №1

The reason why the animation does not repeat is due to CSS needing a frame to initiate the animation when there is no class present.

To resolve this issue, it is recommended to delay adding the class until the next frame.

function triggerAnimation() {
  $("span").removeClass("fade-out");
  requestAnimationFrame(()=>{
    $("span").addClass("fade-out");
  });
}

Answer №2

To refresh the animation, it's important to follow the correct procedure. Using the event animationend is the proper way to achieve this. During this event, the class opacity-effect should be removed.

function resetAnimation() {
    $("span").addClass("opacity-effect");
    $("span").on("animationend", function() {
        $(this).removeClass("opacity-effect");
    });
}
span {
    opacity: 0;
}

.opacity-effect {
    animation-name: animate-opacity-effect;
    animation-duration: 1400ms;
    animation-fill-mode: forwards;
    opacity: 0;
}

@keyframes animate-opacity-effect {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span>Hello World!</span>
<button onClick="resetAnimation()">
    Start animation
</button>

Answer №3

To achieve a smooth transition between removing a class with `removeClass` and adding a class with `addClass`, you can introduce a small delay in two different ways:

Option 1: Using setTimeout

function applyAnimation() {
  $("span").removeClass("opacity-effect");
  setTimeout(() => {
    $("span").addClass("opacity-effect");
  }, 0);
}
span{
  opacity: 0;
}

.opacity-effect {
  animation-name: animate-opacity-effect;
  animation-duration: 1400ms;
  animation-fill-mode: forwards;
}

@keyframes animate-opacity-effect {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Hello World!</span>
<button onClick="applyAnimation()">
   Start animation
</button>

Option 2: Using Cloning

function applyAnimation() {
  const newElement = $("span").removeClass("opacity-effect").clone(true);
  $("span").before(newElement);
  $("span:last").remove();
  newElement.addClass("opacity-effect");
}
span{
  opacity: 0;
}

.opacity-effect {
  animation-name: animate-opacity-effect;
  animation-duration: 1400ms;
  animation-fill-mode: forwards;
}

@keyframes animate-opacity-effect {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Hello World!</span>
<button onClick="applyAnimation()">
   Start animation
</button>

Answer №4

$('span').toggleClass('fade-in');
setTimeout(function(){
 $('span').toggleClass('fade-in');
}, 1500);

Give this a shot 1500 is the time for your animation to take place

Answer №5

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Generating Dropdown from Database</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <style>
    span{
        opacity: 0;
    }

    .opacity-effect {
        opacity: 0;
        -webkit-animation: animate-opacity-effect 1400ms infinite;
        -moz-animation: animate-opacity-effect 1400ms infinite;
        -o-animation: animate-opacity-effect 1400ms infinite;
            animation: animate-opacity-effect 1400ms infinite;
    }

    @keyframes animate-opacity-effect  {
        0%   { opacity:1; }
        50%  { opacity:0; }
        100% { opacity:1; }
    }
    @-o-keyframes animate-opacity-effect {
        0%   { opacity:1; }
        50%  { opacity:0; }
        100% { opacity:1; }
    }
    @-moz-keyframes animate-opacity-effect {
        0%   { opacity:1; }
        50%  { opacity:0; }
        100% { opacity:1; }
    }
    @-webkit-keyframes animate-opacity-effect {
        0%   { opacity:1; }
        50%  { opacity:0; }
        100% { opacity:1; }
    }


  </style>
</head>
<body>
    <span>Greetings, Earthlings!</span>
    <button onClick="activateAnimation()">
       Initiate animation
    </button>

<script>
function activateAnimation() {
  $("span").removeClass("opacity-effect");
  $("span").addClass("opacity-effect");
}
</script>

</body>
</html>

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

How can I effectively import and utilize the Aurelia module with jquery.soap?

Exploring Aurelia's capabilities is new territory for me. In order to call a SOAP webservice, I stumbled upon the jquery.soap module (available at https://www.npmjs.com/package/jquery.soap) as a potential solution. I have included the module in my d ...

What is the process for implementing a unique Angular theme across all components?

I created a unique Angular theme called 'my-theme.scss' and added it to the angular.json file. While it works with most Angular Elements, I am facing issues getting it to apply to certain HTML Elements inside Angular Components. For example: < ...

React.js - jQuery method fails to function

The application utilizes node.js and react.js, specifically the use of react-async. Within a react component, there is a click handler that needs to retrieve the class names - specifically minus_decrement and inline_block. To achieve this, jQuery was integ ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

The picture does not occupy the entire page

Here is a simplified version of my HTML and CSS: @keyframes animatedBackground { from { background-position: 0 0; } to { background-position: 100% 0; } } *{margin:0;padding:0;}/*added as requested*/ .background-image { background-im ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

What is the best term to use for the collection objects that are circulated among jQuery functions?

Is there a commonly accepted name for the objects manipulated by jQuery? jQuery primarily uses chain-able function calls that handle and return collection objects containing different HTML or DOM nodes, which may or may not be interconnected. They are o ...

Scrape embedded content within an IFrame on a webpage with Java

Currently, I am interested in crawling the dynamic content within an IFramed webpage; Unfortunately, none of the crawlers I have tested so far (Aperture, Crawl4j) seem to support this feature. The result I typically get is: <iframe id="template_cont ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

Attempting to generate an endlessly looping carousel of bootstrap cards using PHP

As a beginner in PHP and MySQLi, I am looking to create a basic website with looping statements in PHP to generate cards in the same row with matching size and columns without manually creating them in HTML. I am using Bootstrap, PHP, and MySQLi for this ...

Storing array data locally within an AngularJS application for seamless sharing between two separate applications

I need assistance with persisting and sharing array data var queries = []; between two separate AngularJS applications. One application is for the front end, while the other is for the admin side. Both applications cause the entire page to load when access ...

Learn how to implement Redux login to display the first letter of a user's name and their login name simultaneously

I am implementing a Redux login feature and after successful login, I want to display the first letter of the user's name or email in a span element within the header section. Can anyone provide a solution for this? Below is my Redux login code snippe ...

Instructions on how to automatically close a Bootstrap 5 alert without using jQuery

With the removal of jQuery as a dependency in Bootstrap 5, I have been exploring ways to automatically dismiss an Alert after a set duration using raw Javascript. Below is a snippet of my current approach. I believe there is room for optimization or a bett ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

How to utilize View as a substitute for the div tag in your Web Project

Undoubtedly, when working on a web project, it is common practice to use the div element like this: <div> sample text </div> However, using div in React Native can lead to errors: <View> sample text </View> Is there a way to ...

Designing table rows to resemble full-width cards

Looking for a way to transform the rows of a table into full-width cards while maintaining the row layout? Here's what I have tried so far: tbody>tr { display: block; padding: 1rem 0.5rem 1rem 0.5rem; margin: 1.5rem; border: 1px solid rgba( ...

Is there a way to store a file in a server directory using the <a href='mypdf.pdf'> tag?

I find myself in a bit of a bind. I have a document that needs to be saved in my server directory, which is attached in an <a href='mypdf.pdf'>My pdf</a> tag. The issue is that the filename, mypdf.pdf, is dynamically changing via Jav ...

What is the most reliable method for displaying an SVG shape in any color across various web browsers?

Is there a way to render a 2D SVG shape, which is flat and 100% black, in any color across various browsers? ...

Guide to locating a particular node within an array of nested objects by utilizing the object

Dealing with an array of nested objects, the goal is to compare values with a flat array and update the property matchFound. If the parent's matchFound is true, then all its children should inherit this value. treeData = [{ field: 'make&a ...