Search code examples
jquerycssfadeincss-animations

Image appearing before fade in


Im trying to use some standard jQuery and CSS to get an image to fade in, but after fiddling with the opacity it seems as though if I set opacity to 0 in css, then the image will reappear during the animation, then disappear again once its finished. Any tips?

here is the code:

jQuery

<script>
$(window).scroll(function() {
    $("#me").each(function(){
    var imagePos = $(this).offset().top;
    var topOfWindow = $(window).scrollTop();
        if (imagePos < topOfWindow+650) {
            $(this).addClass("fadeIn");
        }
    });
});
</script>

CSS

@keyframes fadeIn {
    0% {
        transform: scale(0);
        opacity: 0.0;       
    }
    60% {
        transform: scale(1.1);  
    }
    80% {
        transform: scale(0.9);
        opacity: 1; 
    }   
    100% {
        transform: scale(1);
        opacity: 1; 
    }       
}

Solution

  • Here is how you can proceed:

    DEMO

    CSS

    @-webkit-keyframes fadeIn {
        0% {
            -webkit-transform: scale(0);
            opacity: 0.0;       
        }
        60% {
            -webkit-transform: scale(1.1);  
        }
        80% {
            -webkit-transform: scale(0.9);
            opacity: 1; 
        }   
        100% {
            -webkit-transform: scale(1);
            opacity: 0; 
        }       
    }
    @keyframes fadeIn {
        0% {
            transform: scale(0);
            opacity: 0.0;       
        }
        60% {
            transform: scale(1.1);  
        }
        80% {
            transform: scale(0.9);
            opacity: 1; 
        }   
        100% {
            transform: scale(1);
            opacity: 0; 
        }       
    }
    
    .fadeIn {
      -webkit-animation: fadeIn 3s;
              animation: fadeIn 3s;
    }
    
    .me {
      width: 100px;
      height: 100px;
      background: red;
      opacity: 0;
    }
    

    HTML

    <button id="toggle-button">Toggle</button>
    <div id="me" class="me"></div>
    

    JavaScript

    $('#toggle-button').click(function () {
      var el = document.getElementById('me');
      el.classList.add('fadeIn');
      $(el).bind('webkitAnimationEnd oanimationend msAnimationEnd animationend',   
        function(e) {
        this.classList.remove('fadeIn');
      });
    });