1

Can someone please tell me what's wrong with this code? Chrome and Firefox are saying that scrns[i] is undefined though Chrome still runs the code on mouseover.

function nextPrev() {
 if (!document.getElementsByClassName) return false;
 var scrns = document.getElementsByClassName('scrn');
 for (var i=0; i<=scrns.length; i++) {
 // console.log(i);
 scrns[i].onmouseover = function() {
 // console.log('foo');
 }
 }
}
window.onload = nextPrev();

I've tested that the for loop is working and tried to pin down where the problem is coming from in every way I know how. I'm even looking at an example I took from a book sometime ago and cannot understand why scrns[i] would be undefined.

Any help greatly appreciated!

Cloudy
7,5297 gold badges64 silver badges98 bronze badges
asked Mar 1, 2012 at 19:25
2
  • 1
    window.onload = nextPrev(); should (probably) be window.onload = nextPrev; Commented Mar 1, 2012 at 19:28
  • 2
    Also, you might look into jQuery. Your code could be written in 2 lines with jQuery. Commented Mar 1, 2012 at 19:32

3 Answers 3

5

You're using <= when looping through. But remember that arrays are indexed starting at 0, not 1. So an array with 10 elements has a length of 10, but elements 0-9. Change the following:

for (var i=0; i<=scrns.length; i++) {

to:

for (var i=0; i < scrns.length; i++) {
answered Mar 1, 2012 at 19:28
Sign up to request clarification or add additional context in comments.

2 Comments

I have no idea how that equals got there and didn't even see it, long day! thank you :)
@frank I've had those days too. :)
5

You are looping too far. If i is equal to scrns.length then it is beyond the end of the array. Remove the = in your stop condition:

for (var i=0; i < scrns.length; i++) {
Cloudy
7,5297 gold badges64 silver badges98 bronze badges
answered Mar 1, 2012 at 19:27

Comments

0

You have an off by one error. Changing <= to < should fix your issue. You can use loop invariants in the future to make sure that you don't go over.

http://en.wikipedia.org/wiki/Loop_invariant

In general though, when looping through an array, begin with the iterating counter at 0 and then loop so long as the counter is less than the length of the array.

answered Mar 1, 2012 at 19:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.