I am trying to make a simple image rotator that will rotate through a number of set images in a php array. The array out puts the image correctly, the styles work, even the JQuery that fades out the active element. It just can’t find the next element and using console.log(), I know it is calculating the correct one. I even tried to put a number (like 3) in .eq() to see if it will select that element, and it won’t. Here is my code:
PHP code:
$randomNumber = rand(0);
$performanceImages = array("09_15_11-Lorton_opening_088.jpg",
"09_15_11-Lorton_opening_120.jpg",
"09_15_11-Lorton_opening_123.jpg",
"09_15_11-Lorton_opening_125.jpg",
"09_15_11-Lorton_opening_126.jpg",
"09_15_11-Lorton_opening_128-150x150.jpg",
"09_15_11-Lorton_opening_131.jpg",
"09_15_11-Lorton_opening_132.jpg",
"09_15_11-Lorton_opening_135-199x300.jpg",
"09_15_11-Lorton_opening_137-150x150.jpg",
"09_15_11-Lorton_opening_144.jpg",
"09_15_11-Lorton_opening_161.jpg");
$randomNumber = rand(0, (sizeof($performanceImages) - 1) );
for ($cnt = 0; $cnt < sizeof($performanceImages); $cnt++) {
if ($cnt == $randomNumber) {
echo '<div id="rotator-image" class="active" style="display:block;"><img src="'.get_bloginfo('template_directory').'/images/rotation-images/'.$performanceImages[$cnt].'" /></div>';
} else {
echo '<div id="rotator-image" style="display:none;"><img src="'.get_bloginfo('template_directory').'/images/rotation-images/'.$performanceImages[$cnt].'" /></div>';
}
}
CSS:
#sidebar-image-rotator {
width: 180px;
height: 263px;
position: relative;
}
#rotator-image {
position: absolute;
top: 0;
left: 0;
}
JQuery:
function sidebarImageRotator(){
var count = $("#sidebar-image-rotator").children("#rotator-image").length;
//console.log(count);
var active = $('#rotator-image.active').index();
//console.log(active);
if ((active + 1) < count) {
var next = active + 1;
} else {
var next = 0;
}
//console.log(next);
//change div classes
$("#rotator-image.active").fadeOut('slow', function () {
$("#rotator-image.active").removeClass("active").css("display","none");
$('#sidebar-image-rotator').find('#rotator-image').eq(next).addClass('active').fadeIn('slow', function () {
$('#rotator-image.active').css('display', 'block');
})
});
}
function startTimer() {
//timer for the box
window.timer = window.setInterval(function() {
$("#sidebar-image-rotator").timer();
}, 7000);
jQuery.fn.timer = function() {
sidebarImageRotator();
}
}
startTimer() is being called with the page is loaded.
HTML id’s must be unqiue. jQuery is only ever going to find the first id, change to using classes instead.
Something like the following
Example PHP loop :
Example CSS
Example jQuery