Search code examples
angularjssettimeoutng-class

How to change the color of a button for only a few seconds using angular?


I want my button to change color when clicked. Also only change it for 3 seconds and then go back to the default color. I have been looking at similar questions postet on stack overflow but whatever I tried it didn't work (don't know why my code isn't working). Also Im not sure how to make it change the color for only 3 seconds. So far I 1. $scope.isActive=false; 2. then in the controller, I changed it to true if clicked:

$scope.copyText = function(text){
  $scope.isActive = !$scope.isActive;
  console.log('clicked in controller');
  Clipboard.copy(text)
}

html:

<div class="inner-single" ng-hide="updateInfo">
    <h3>Login Details:</h3>
    <h5 ><span class="categories">Username:</span> {{account.username}}<button 
         ng-click="copyText(account.username)" ng-class="isActive ? 'noColor' : 'hasColor'" >
    Copy</button></h5>    
  <button class="btn btn-large btn-default" ng-click="showForm()">Update Info</button>

CSS

 .copy-button {
  .copy-button.hasColor {
    color:green;
  }
  .copy-button.noColor {
   color: grey; }
  font-size: 12px;
  padding: 0px, 3px, 0px, 3px;
  margin-left: 5px; }
}

For keeping track of the seconds, I would use the setTimeout function, however, not sure how to combine it with angular and changing the color..

Happy about suggestions! Thank you!


Solution

  • You could use $timeout here with 3000(3 sec), and the again preset isActive flag over there.

    Code

    $scope.copyText = function(text){
      $scope.isActive = !$scope.isActive;
      console.log('clicked in controller');
      Clipboard.copy(text);
      //don't forget to add `$timeout` in controller dependency.
      $timeout(function(){
          $scope.isActive = !$scope.isActive;
      }, 3000);
    }
    

    It seems like your CSS rules are incorrect, you have to correct them or otherwise put copy-button class over button

    .copy-button.hasColor {
      color: green;
    }
    
    .copy-button.noColor {
      color: grey;
    }
    

    Demo Here