KyleNumann
5/11/2016 - 8:14 PM

Switch static image out for animated gif on hover

Switch static image out for animated gif on hover

<div class="gif-switch">
  <!-- add class 'gif-switch' to wrapping element, whose hover should trigger the switch -->
  <img src="img/analyze_3_single.gif" class="hidden"><!-- preload the gif -->
  <img src="img/analyze.png" class="gif-switch-img" data-gif-src="img/analyze_3_single.gif" data-orig-src="img/analyze.png">
</div>


<script>
/*
  Gif Switch Code
  ---------------
  Easily switch an image from a static img to animated gif,
  including a delay for css fade-out of original image.
  Markup looks like such:
  <img src="analyze.png" class="gif-switch-img" data-gif-src="analyze.gif" data-orig-src="analyze.png">
*/
$(".gif-switch").mouseenter(function(e){
  var target = $(e.currentTarget);
  var gifSrc = target.find('.gif-switch-img').attr('data-gif-src');
  timer = setTimeout(function(){
      target.find('.gif-switch-img').attr('src', gifSrc);
  },200);
}).mouseleave(function(e){
  var target = $(e.currentTarget);
  clearTimeout(timer);
  var origSrc = target.find('.gif-switch-img').attr('data-orig-src');
  target.find('.gif-switch-img').attr('src', origSrc);
});
</script>

<style>
/* Sass code here:

.gif-switch {
  .gif-switch-img {
    -webkit-backface-visibility: hidden;
  }
  &:hover {
    .gif-switch-img {
      animation: fadeOutIn 0.4s ease-in;
      animation-fill-mode: forwards;
      animation-iteration-count: 1;
    }
  }
}
@keyframes fadeOutIn {
  0% {
    opacity:1;
  }
  50% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

*/
.gif-switch .gif-switch-img {
  -webkit-backface-visibility: hidden;
}
.gif-switch:hover .gif-switch-img {
  animation: fadeOutIn 0.4s ease-in;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}
@keyframes fadeOutIn {
  0% {
    opacity:1;
  }
  50% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}
</style>