I’m not sure what I’m doing wrong. I’m trying to get the background image of my div to change over time. I got the jQuery function from this site but its not working for me. Any clue what I’m doing wrong.
jQuery
$(window).load(function () {
var images = ['wave_01.png', 'wave_02.png'];
var i = 0;
function changeBackground() {
$('main').css('background-image', function () {
if (i >= images.length) {
i = 0;
}
return 'url(' + images[i++] + ')';
});
}
// Call it on the first time
changeBackground();
// Set an interval to continue
setInterval(changeBackground, 3000);
});
HTML
<div class="main"></div>
CSS
.main {
background-image: url(../images/wave_01.png);
background-repeat:no-repeat;
background-size: 100% 40%;
}
Is your path to images correct in your JavaScript ? You have:
But in your CSS it’s:
This suggests the images are in the same folder as the Javascript. Is that the case ?
This isn’t necessarily incorrect if your project is structured that way, but worth checking. I think in reality it probably is an error though, as it would need your Javascript to be in “images” folder too to work.
If your CSS and Javascript are all in the same HTML file, make the paths the same, i.e.
If you’re not sure, try both with absolute paths ( e.g.
'/images/wave_01.png') instead.Also, not sure it it’s just a typo or not, but the selector
$('main')should definitely be$('.main')instead.