Jeremy Jeremy - 4 months ago 11
jQuery Question

Background-change works only in chrome + $.preload doesn't work

I made a script to change background images every 8 seconds. Everything works fine in chrome, but in other browsers it doesn't. (Tested on Safari, Edge, IE 9 - 11 and Mozilla). I also have the jQuery preload plugin, but it actually doesn't preload the images. The console doesn't show me any errors, so I don't know why it doesn't work.
Code:

var c = 1,
nimg = $('header .background .img').attr('data-bg'),
bgpath = $('header .background .img').css('background').match(/"(.*)"/),
imgpath,
imgs = [],
startpath,
startpoint,
selector = 'header .background .content .text',
time = 8000;
if (path[1] == 'diwerf') {
startpath = '/'+path[1];
} else {
startpath = '/templates';
};
startpoint = bgpath[1].search(startpath);
bgpath = bgpath[1].slice(startpoint);

for (var g = 1; g <= nimg; g++) {
imgpath = bgpath.replace(/[0-9]/g, g);

imgs.push(imgpath);
};

$.preload(imgs);

function removeText() {
setTimeout(function() {
$(selector).fadeOut('slow', function() {
$(this).removeClass('animated').removeAttr('style');
});
}, time-600);
}

removeText();

setInterval(function() {
if (c == nimg) {
c = 0;
};
c++;
bgpath = bgpath.replace(/[0-9]/g, c);
$('header .background .img').css('background', 'url('+bgpath+') center center no-repeat');

setTimeout(function() {
$(selector+'-'+c).addClass('animated');
}, 600);

removeText();
}, time+100);


It doesn't do anything, not even adding the 'animated' class.

Here you can see the website: http://www.testing.dw-erfolg.eu/

Thanks for help!

Answer

You are using a shorthand CSS property, which is not guaranteed in all browsers.

bgpath = $('header .background .img').css('background').match(/"(.*)"/),

Instead you should use .css('backgroundImage')

Make sure you also change line 42:

$('header .background .img').css('backgroundImage', 'url('+bgpath+')');