user984621 user984621 - 7 months ago 39
HTML Question

jQuery - Simple Image Rotator

On fiddle I found a simple rotator and trying to make it work in my death-simple HTML page.

The page example is here:

<!doctype html>
<meta charset="utf-8">
<script src="//"></script>
img { max-height: 100px }
.rotator img { max-height: 200px; border: dashed 5px pink; }​
$(document).ready(function() {
var $rotator = $(".rotator");
setTimeout(Rotate, 1000);

function Rotate() {
var $current = $rotator.find("img:visible");
var $next = $;
if ($next.length == 0) $next = $rotator.find("img:eq(0)");
setTimeout(Rotate, 5000);


<img src=""/>
<img src=""/>
<img src=""/>

<div class="rotator">
<a href="">
<img src=""/>
<a href="">
<img src=""/>
<a href="">
<img src=""/></a>

<label />​


The simple script should regularly switch images, but instead of that are just displayed all 3 images. And the alert message is not displayed.
I've tried to debug the code and when I remove the function
, an alert message appears on the page.

Why the function
is not working?


$.next() gets the immediate element in the set. Your set only contains visible images - i.e. only one. How could there be a next element?

Working fiddle:

All I have done is changed the $.next() call into an $.index() request and modulo-ed it by the number of images (so you'll never get a non-existent image). Let me know if you need anything else modified to it or any explanations!