I have some links and want to pass the focus one by one automatically.
I’m using the code below. Works fine passing the focus but only once.
The first time the focus pass, the link change the color, then pass to the next. The one before gets black again and the next is painted red. No problem.
But when its reach the final link doesn’t restart.
var i = 0;
var letras = document.getElementsByTagName("a");
function pasaLink() {
if (i == 0) {
letras[letras.length-1].style.color = "black";
} else {
letras[i-1].style.color = "black";
}
letras[i].style.color = "red";
letras[i].focus();
i++;
if (i > letras.length) {
i= 0;
}
setTimeout("pasaLink()",2000);
}
With the final if and i=0; I’m trying to get back to the initial index when reach the final element, and then restart to iterate the entire collection of links in letras.
This function is called in the body.onload().
Any ideas why its not working?
Change your
ifto:Working example:
http://jsfiddle.net/nivas/Nn62Q/
(click the
OrigButton to see the behavior of your code and theNewbutton to see the behavior of the new one. I have added atry...catchto show the error)Explanation:
Let us say there are five
atags.You make
i = 0wheni > 6(i.e.,6). But whenibecomes5,letras[i].style.color = "red";at the beginning of the function fails and an exception is throws a exception. The flow stops here so theif (i > letras.length)will never be reached.