Search code examples
jquerycsswordpressbackground-imagefadein

jQuery(document).ready(function(){ isn't waiting for Background Image to load first before Fadein


I'm having trouble with jQuery(document).ready(function(){ - my issue is that it's not waiting for the background image to load first before fading in when I clear the cache. So what happens is there's a delay before the wrapper fades in then the image is visibly scaling down the screen as it loads.

I'm building with Headway Themes on Wordpress.

It's making me go insane :)

CSS:

@-webkit-keyframes fade-in {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

.background-image {
  background: url('http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg') no-repeat center center fixed;

  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  opacity: 0;

  -webkit-animation-name: fade-in;
  -webkit-animation-duration: 1s;
  -webkit-animation-timing-function: ease-in;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-delay: 2s;
  -webkit-animation-fill-mode: forwards;
}

.background-image.visible {
  opacity: 1;
}

jQuery:

  jQuery(document).load(function() {
  jQuery('.background-image').on('webkitAnimationEnd', function(e) {
    jQuery(this).addClass('visible');
  });
});

I have tailored this from: http://codepen.io/graygilmore/pen/hxpEt

Any solutions are beyond appreciated!

Thanks, Danielle

I have just made the site live (it's VERY much under construction ha) - you'll see the background image on load: http://www.aliceandowl.com Thanks guys!

So far all answers given are doing the same thing, and the issue still remains that the Fadein doesn't wait for the Background Image to load first.


Solution

  • SOLVED! I took a break and came back to it which usually helps, I came across the following which now works perfectly, thank you for all your help guys!

    CSS:

    .background-image {
      background: url('http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg') no-repeat center center fixed; 
    
        display: none;
    
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0; 
    }
    

    jQuery:

    jQuery(window).load(function(){
        jQuery('<img/>').attr('src', 'http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg').load(function() {  
          jQuery('.background-image').fadeIn(2000);
        });
      });
    

    Now I'm going to have the biggest glass of wine ;)