Malcolm Tanti Malcolm Tanti - 12 days ago 6
CSS Question

JQuery, not animating my background image when trying to refresh

I'm talking about this site here: malcolmtanti.com

I am using this function:

<script>
var image = new Image();
image.onload = function () {
$('header').animate({opacity: 1}, 2000);
}
image.src = "./images/background.jpg";
</script>


to animate the
fade in
of my main background image and the title etc. It should fade in the header element in my css.

This is the CSS:

header{
position: relative;
background: url(../images/background.jpg) no-repeat top center;
background-size: cover !important;
-webkit-background-size: cover !important;
/*height: 700*/
top:50px;
min-height:95%;
max-width: 100%;
overflow: hidden;
opacity:0;
}


For some reason, the first time I access the site, the picture loads for me, but once I press refresh, the opacity of the header tag is remaining 0. How can this be?

Answer

It might be a problem with the browser caching the image so that when you refresh the page it doesn't fire the animation since the image is already preloaded.

Try loading the image with a unique id (like the current time) to prevent this.

<script>
  var image = $('<img/>');
  var srcText = './images/background.jpg?t=' + new Date().getTime();
  image.attr('src', srcText).load(function() {
    $(this).remove();
    $('header').animate({opacity: 1}, 2000);
  });
</script>