Tips for applying various classes using ngClass to enable an animation when a value changes compared to when that value is true when the page first loads

I need some help with a coding issue, could someone assist in making my question clearer?

I'm working on creating an animation that triggers when the value of an object changes. I used ngClass to assign a class to an element based on the object's value. However, if the initial value already meets the condition for the class, the animation still plays. How can I prevent this from happening? User input cannot be relied upon to trigger the change, as there are asynchronous events that may alter the object's value.

JSFiddle example: https://jsfiddle.net/s6cdgyLb/ Unfortunately, AngularJS doesn't work well with JSFiddle... Plunkr example: https://plnkr.co/edit/LPJXRq1SWQWrqGaow5tR?p=preview

This is the desired flow:

Page Load --> Question Answered --> color green

User Answers Question --> Animate --> color green

The current flow looks like this:

Page Load --> Question Answered --> Animate  --> color green

User Answers Question --> Animate --> color green

var myApp = angular.module('myApp2', []);

myApp.controller('myController', ['$scope', function($scope){
    $scope.list = [
        {
           value: "Some stuff",
           answered: true
        },
        {
           value: "More Stuff",
           answered: false        
        }
    ];
}]);

myApp.directive('questionCheckbox', function(){
    function link(scope, element, attrs){
        element.bind('click', function(){
            scope.$apply(function(){
                question.answered = element.checked;
            })
        });
    };
    return {
        link: link
    }
});
        @keyframes answered {
            0% {background-color: inherit;}
            70% {background-color: hsla(125, 100%, 34%, 0.65);}
            100% {background-color: hsla(125, 100%, 34%, 0.2);}
        }        
        
        .answered {
            animation: answered 2s;
            animation-fill-mode:forwards;
        }
<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.10/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="myApp2" ng-controller="myController">
      <div ng-repeat="question in list">
        <div ng-class="{answered: question.answered}">
          <input type="checkbox" ng-model="question.answered">
          <span>{{question.value}}</span>
        </div>
      </div>
    </div>
  </body>

</html>

Answer №1

To achieve the desired effect, consider implementing CSS transitions instead. When using Angular, the template is initially rendered with the "responded" class applied, preventing the transition from being triggered.

.responded {
  background: hsla(125, 100%, 34%, 0.2);
  transition: 2s;
}

Answer №2

Here are some helpful tips. Please note that the animation might get interrupted if another checkbox is clicked before it completes. I made modifications to your plunkr, and you can view them in the updated version.

Below is the code snippet I used in the controller to manage the .plain and .animated classes:

$scope.setIndex = function (index, answered) {
    if (answered) {
        $scope.selectedIndex = index;
    } else {
        $scope.selectedIndex = -1;
    }
};

I utilized three classes for styling control:

.answered {
    background-color: hsla(125, 100%, 34%, 0.2);
}

.animated {
    animation: answered 2s;
    animation-fill-mode:forwards;
}

.plain {
    background: none;
}

Lastly, here is the HTML segment I added to handle the .animated and .plain classes:

<div ng-class="{answered: question.answered, animated: $index === selectedIndex, plain: !question.answered}">
    <input type="checkbox" ng-model="question.answered"
           ng-click="setIndex($index, question.answered)">
    <span>{{question.value}}</span>
</div>

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

The .htaccess directive aimed at eliminating .html from the URL appears to be malfunctioning

Struggling to remove the .html extension from your page URLs? I've been trying various methods with the .htaccess file, but nothing seems to be working. I created an .htaccess file and placed it in the public_html directory. The code snippet I'm ...

Automatically retrieve the generated PDF file upon completion (Node.js and Express)

I've been utilizing the node module html-pdf to seamlessly convert my HTML into PDF format. The conversion process goes smoothly, but I'm encountering difficulties when it comes to downloading the file once it's been generated. Below is the ...

Step-by-step guide to achieving a File div effect using CSS

Wondering how to achieve this specific effect within a div using CSS? click here for visual reference I attempted it using the before and after elements, but I struggle with these tags: check out this image for details Apologies if my question is unclear ...

Tips for changing the scope value with a click event on a custom element

Within my directive, I am dynamically replacing the template based on the index values. When a user clicks on the template, I need to assign the clicked directive value to the scope value. The challenge I face is that I cannot access the scope directly wi ...

Having trouble verifying the dropdown menu in bootstrap

I'm having trouble validating the dropdown using bootstrap. I've tried data-validation and other methods, but nothing seems to work... All of the other validation fields are functioning correctly, except for the dropdown where I want to require ...

Trouble aligning text next to boxes in Bootstrap Modal

Having trouble aligning the input text boxes in a modal form created with Bootstrap? The fields are currently showing under the labels instead of beside them. Looking for suggestions on how to fix this alignment issue. <button type="button" class= ...

Accessing the DOM element from an AJAX response using JavaScript

After receiving an AJAX response containing HTML, how can I extract a specific element from the DOM using JavaScript? The issue I'm facing is that when I try to use getElementById on the returned HTML div, it returns null. It appears that the DOM has ...

Find the attribute value, locate corresponding values on different elements, and make changes to the CSS styling

Currently, I am attempting to retrieve the value of an attribute called 'data-location', and then locate that same value somewhere else in the form of an ID. Once matched, I aim to modify the CSS for that specific value. Although I have a code s ...

Material UI Paper component does not extend to full viewport height

My React component includes a Material UI <Paper> component that acts as a background. This <Paper> is nested inside a <ThemeProvider>, which in turn is nested within a <div>, and then further nested inside the <body>. I have ...

activating a button following the selection of a checkbox

My code includes a submit button that is currently disabled. I am looking to enable it when the user clicks on the "I agree" checkbox using jQuery. Can someone assist me with this? My code is written in HTML, JavaScript, and jQuery. <input id="agree" ...

I'm struggling to successfully insert and retrieve data from a MySQL database using Express.js. I need to figure out how to make these operations work seamlessly across the board

HTML CODE <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>CHAT APPLICATION</title> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+ ...

Can you explain the concept of "entity-body" in relation to Digest Authentication?

Incorporating digest authentication and noticing mention of "entity-body" in the document for auth-int authentication. Is this referring to the HTML header and body, or just the HTML header section? For more information on digest authentication, check out ...

The following error occurred: "Item cannot be serialized into JSON format."

I'm working on a Python code that looks like this: my_list=json.dumps(data_list) payload = {'data_list' : my_list} requests.get("http://127.0.0.1:8000/myhorizon/resource_usage/index", json=payload) After that, I use AJAX to create a curv ...

Eliminating the gap between three HTML columns

I am facing an issue with reducing the space between 3 col-md-4 elements in my code. I attempted to decrease the margin between them while adjusting the padding on the first and last columns. However, this solution resulted in the image columns becoming mi ...

Tips for dynamically updating an AngularJS table cell value from a database without needing to refresh the entire page

I have developed an application that utilizes xeditable to display a table populated with data from a mySQL database. The challenge I am currently facing involves the dynamic nature of the database table, as it constantly undergoes changes in the backgrou ...

Showcasing Bootstrap navigation exclusively on mobile devices and including a scroll function on desktop screens

I am working on customizing a Bootstrap 4 top-sticky nav to only be visible on mobile devices. Using CSS (d-block d-md-none) can achieve this, but on desktop, I want the menu to fade in as the user scrolls down past a certain point and disappear when scrol ...

Moving elements using CSS

Hi, I've been facing this issue with my web development since the start. Whenever I zoom in, the container also moves along. Is there any way to fix this problem? .darkslidecont{ width: 200px; height: 50px; position: relative; bac ...

The Angular unit tests function properly when executed in a browser, but encounter errors when running in Chutz

My Angular module utilizes the angular ui bootstrap typeahead directive. I am currently working on unit testing it using qunit and chutzpah. When running the unit test through a browser, everything runs smoothly and passes. However, when executing it with ...

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

Guide to Positioning Pre-Loader in the Center on Mobile Devices

Despite trying numerous solutions, I'm struggling to center my pre-loader on mobile devices. It looks fine on desktop and mobile landscape orientations, but whenever I switch to mobile portrait, it just won't center properly. CSS: .load ...