Clay Banks
Clay Banks

Reputation: 4581

Fade In an Image on Load

I have an angular js directive that replaces an image when it is loaded

.directive('imgOnLoad', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('load', function() {
        element[0].src = scope.obj.image_url;
      });
      element.bind('error', function(){
        console.log('failure!');
      });
    }
  };
})

And my image tag

<img src="img/default.png" img-on-load>

This works well enough, however I'm to add a fade effect when the default image is replaced. I'm thinking it would be overkill if I brought in ngAnimate just for this task - can it be done natively through angular or through some simple CSS?

Any help is appreciated!

Upvotes: 0

Views: 844

Answers (1)

Amal
Amal

Reputation: 3426

Try this code

var demo = angular.module('demo', []);
demo.directive('imgOnLoad', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('load', function() {
      if(scope.count==0){
      console.log("loaded "+(scope.count+1)+" time");
      setTimeout(function(){ 
      	$('#imgID').addClass('imgInitial');
      }, 1000);
      setTimeout(function(){ 
        element[0].src = "https://dummyimage.com/600x400/F7921E/fff";
      	$('#imgID').addClass('imgAnimate');
        $('#imgID').removeClass('imgInitial');
      }, 3000);
      scope.count=1;
      }
      });
    }
  };
});
.imgInitial {
    opacity: 0;
-webkit-transition: opacity 2s ease-out;
transition: opacity 2s ease-out;
}
.imgAnimate {
    opacity: 1;
    -webkit-transition: opacity 3s ease-in;
    transition: opacity 3s ease-in;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div ng-app='demo'>
    <div ng-init="count=0">
      <img id="imgID" src="https://dummyimage.com/600x400/000/fff" img-on-load>
    </div>
</div>

Upvotes: 1

Related Questions