Button click triggers CSS animation

Check out the interactive demo

$(document).ready(function(){
  $('#btn-animate').click(function(){
    animate();
  });
  $('#btn-remove').click(function(){
    $('.to-animate').removeClass('animate');
  });

  function animate(){
    $('.to-animate').removeClass('animate');
    $('.to-animate').addClass('animate');
  }
});

In the demonstration, clicking on the "ANIMATE" button should add an 'animate' class to a div and trigger an animation (color change). However, subsequent clicks do not re-trigger the animation as expected. The goal is to remove and immediately re-add the 'animate' class each time the button is clicked.

The current implementation does not achieve this desired behavior. Surprisingly, if you first click the "REMOVE" button to eliminate the 'animate' class, then proceed to click the "ANIMATE" button, the animation works again.

Can anyone provide insight into why the initial button click fails to produce the intended outcome? Additionally, how can we ensure that the animation is triggered consistently whenever the "ANIMATE" button is pressed?

Answer №1

Most browsers typically do not update the user interface until all JavaScript has finished running. They are clever enough to detect that after the second click on the animation button, the Document Object Model (DOM) remains unchanged before and after. Therefore, no action is taken.

The simplest solution is to remove the class first and then set a timer to add it back after a short delay.

function animate(){
    $('.to-animate').removeClass('animate');
    setTimeout(function(){$('.to-animate').addClass('animate');}, 10);
}

Answer №2

It appears that everything is functioning as expected, as I have checked the link and it is working properly.

Have you considered verifying if the class exists before removing it?

function animate(){
    if(!$('.to-animate').hasClass('animate')){
        $('.to-animate').addClass('animate');
    }
}

Answer №3

Forget about using a CSS class for the animation and opt for jQuery instead.

$(document).ready(function(){
  $('#animate-button').click(function(){
    $(this).animate(
    "opacity":"0",
    // add your desired animation code here
    }, 300);
});

Answer №4

If you're looking to add some dynamic effects to your website, jQuery provides a convenient solution with its built-in function toggleClass

$(document).ready(function() {
  $('#btn-animate,#btn-remove').click(function() {
    $('.to-animate').toggleClass('animate');
});

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

Can you explain the process of exception handling in jQuery and ASP.NET MVC?

I've been experimenting with my code recently, trying to see what would happen if I made a particular change. So, here's what I did: I loaded up my ASP.NET MVC page and then paused my MSSQL 2005 database. Next, I clicked on a link that triggered ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...

Can JavaScript be used to retrieve time information from a central location?

In the process of developing a PhoneGap application, I am restricted to using only HTML, CSS, and JavaScript. I am seeking guidance on how to retrieve time information from a centralized server using strictly JavaScript. Is it possible to achieve this by ...

How to use AngularJS directives to replace text with stars (*) in HTML

I am in need of a textarea control that has the ability to be masked, meaning that the text displayed should appear as stars instead of the actual characters. Since I might have multiple textareas in my form, saving the actual text in one variable and usi ...

Troubleshooting issues with jQuery toggle in Internet Explorer 7: Adjusting position and height for

A script I created can toggle the visibility of a hidden div. The height of the page adjusts automatically on Firefox, Safari, and Chrome. However, when using Internet Explorer 7, the div overlaps the contents at the bottom. I am currently using Joomla as ...

How can you hide specific elements in HTML/CSS based on window size without relying on media queries?

How can I create an HTML/CSS toolbar where specific elements disappear completely when the browser size is decreased, similar to how the favorites bar functions in most browsers? The toolbar should be able to display a varying number of items. In this cas ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

Retaining specific items in a collapsed Bootstrap Navbar

I am looking to keep certain items in my navigation bar visible, but also have a collapse toggle when the window becomes too small on the right side. Example: LOGO item item item Sign In Sign Up When collapsed: LOGO ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

Simulating an ES6 module that returns a factory function for moment.js

Disclaimer: I'm a beginner with Jest so please bear with me. I'm currently working on testing a Vue2.js filter named DateFilter using Jest. This filter simply formats a date that is passed to it. DateFilter.js import Vue from 'vue'; ...

Achieving a sticky scrollbar effect in CSS/JavaScript for scrolling within nested divs

I am trying to create a table with vertical scrolling for the entire table content. Additionally, I need two columns within the table to be scrollable horizontally, but the horizontal scrollbars disappear when the vertical scrollbar is present. How can I k ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Adjusting the height of a Jquery Fancybox to allow for scrolling down

I've implemented fancybox to display certain pages on my website, but I'm struggling with setting a fixed height and enabling scrolling for content that exceeds this height within the fancybox. Here are the parameters I have used: <script> ...

Access data from previous request and transmit it to another request in a Node.js environment

I am facing a situation where I need to extract the parsed json response from a variable in a POST request, store it in a new variable, and then pass that variable in the headers for a subsequent GET request. However, my current approach is not yielding th ...

Executing the JavaScript function only a single time is what you're looking

I'm having trouble getting this script to work correctly on my website. It is supposed to trigger an alert when the specified id is in the viewport, but the issue I am encountering is that the alert keeps popping up repeatedly while the id is still vi ...

Utilize the power of MYSQL and PHP in conjunction with an HTML form to

Having trouble with a basic PHP/SQL search bar for my database. The search results are not showing up even though the search bar appears on the page. When I type something, it doesn't reflect in the URL. Below is the code snippet. I am connecting to t ...

What could be causing the pageLoad function on certain ASP.net pages to not fire for my user control?

Currently, I am developing an ASP.net application. A user control that I created called LocationSelector was working perfectly. However, I encountered an issue when trying to use it within an ASP:UpdatePanel. After researching on SO, I realized that movin ...

Refreshing Three.js Scene to its Initial State

I am in the process of developing a Visual Editor where I can manipulate objects by adding, deleting, and transforming them. Currently, my scene only consists of a 5000x5000 plane as the floor. I am looking for a way to reset the scene back to its origin ...