Malcolm Tanti Malcolm Tanti - 1 year ago 74
CSS Question

JQuery, not animating my background image when trying to refresh

I'm talking about this site here:

I am using this function:

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

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:

position: relative;
background: url(../images/background.jpg) no-repeat top center;
background-size: cover !important;
-webkit-background-size: cover !important;
/*height: 700*/
max-width: 100%;
overflow: hidden;

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 Source

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.

  var image = $('<img/>');
  var srcText = './images/background.jpg?t=' + new Date().getTime();
  image.attr('src', srcText).load(function() {
    $('header').animate({opacity: 1}, 2000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download