2

I was able to make my website header change it's background after certain time, but it doesn't look good when it's blinking.

Here is the website. Is there anyway to change duration of action? I tried to get it done with css animation, but turns out that "background:" is not gonna work like "background-color:" property for some browsers. Anyway here is my code, could you please advice me something. Thank you!

$(document).ready(function(){
var header = $('.header');

var backgrounds = new Array(
    'url("wp-content/themes/the-best-of-the-old-school/pics/header-bg.jpg")', 'url("wp-content/themes/the-best-of-the-old-school/pics/fire-bg.jpg")'
);

var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background', backgrounds[current]);
}

setInterval(nextBackground, 5000);

header.css('background', backgrounds[0]);

});
Tharif
  • 13,794
  • 9
  • 55
  • 77
  • you should start the preload of `current + 1` image when you're showing the `current` image, if the blink effect is due to the loading time – Fabrizio Calderan May 27 '15 at 10:17

2 Answers2

1

You can use jQuery Animate

Replace this line of code

header.css('background', backgrounds[current]);

With the following

header.animate({opacity: 0}, 'slow', function() {
    $(this)
        .css({'background-image': backgrounds[current]})
        .animate({opacity: 1});
});

see the answers here and here

Community
  • 1
  • 1
Sandeep Kumar M
  • 3,841
  • 3
  • 38
  • 59
0

You can define your background-images in different CSS classes:

.bg-0 {
    background: url("wp-content/themes/the-best-of-the-old-school/pics/header-bg.jpg");
}
.bg-1 {
    background: url("wp-content/themes/the-best-of-the-old-school/pics/fire-bg.jpg");
}
...

and then only toggle the different classes on the header:

var backgrounds = [1,2,3,4,5,6];

function nextBackground() {
    current++;
    current = current % backgrounds.length;
    header.removeClass("bg-"+(current-1)).addClass("bg-"+current);
}

This will make sure all the images get loaded without further ado. By the time you toggle first time probably all the images will be available. Ofc this will load all the images at page load, which means that even though a person might not stay long enough to see all images, they would be loading them nonetheless.

connexo
  • 53,704
  • 14
  • 91
  • 128