Reputation: 35
I would like to change the background of a div in a loop between 9 different Images. I tried to use code I found here on stackoverflow, but something went wrong... I am new to Java, so I cant find my mistakes.
My CSS where I want to change IMG:
.ch-img-1 {
background-image: url(Images/round280/1.png) ;
}
My code:
<body>
<ul class="ch-grid">
<li>
<div class="ch-item ch-img-1">
</div>
</li>
</ul>
<script language="JavaScript">
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = '/Images/round280/1.png';
backgrounds[1] = '/Images/round280/2.png';
backgrounds[2] = '/Images/round280/3.png';
backgrounds[3] = '/Images/round280/4.png';
backgrounds[4] = '/Images/round280/5.png';
backgrounds[5] = '/Images/round280/6.png';
backgrounds[6] = '/Images/round280/7.png';
backgrounds[7] = '/Images/round280/8.png';
backgrounds[8] = '/Images/round280/9.png';
function changeBackground() {
currentBackground++;
if(currentBackground > 2) currentBackground = 0;
$('ch-grid.ch-item.ch-img-1').fadeOut(100,function() {
$('ch-grid.ch-item.ch-img-1').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('ch-grid.ch-item.ch-img-1').fadeIn(100);
});
setTimeout(changeBackground, 2000);
}
$(document).ready(function() {
setTimeout(changeBackground, 2000);
});
</script>
</body>
Upvotes: 3
Views: 982
Reputation: 2668
The way you're selecting the div isn't correct. ch-grid
is a class so you need to use a '.' as a prefix: .ch-grid
would be the correct way to select the ul
. Because you want to select the div
contained within the ul
you need a space between the parent class (ch-grid
) and the child classes (ch-item
and ch-img-1
). Once the selector is correct, you can reference the object using $(this)
So your updated JQuery would look like the below:
function changeBackground() {
currentBackground++;
if (currentBackground > 8) currentBackground = 0;
$('.ch-grid .ch-item.ch-img-1').fadeOut(100,function() {
var $this = $(this);
$this.css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$this.fadeIn(100);
});
setTimeout(changeBackground, 2000);
}
Upvotes: 3