Reputation: 79
Here is a bit of code that's responsible for changing the pictures in a carousel on residentadvisor.net. Click the 'right' arrow, the picture changes and the dot navigation moves right, click the 'left' arrow, picture changes and it moves left. If you're at the beginning of the dot navigation series and click left, it goes to the end, otherwise the picture displayed is determined by the data
attribute of whichever dot you clicked.
n.attr("id") == "right" ? currentIndex == $("#slider li").size() -
1? currentIndex = 0 : currentIndex++ : n.attr("id") ==
"left" ? currentIndex == 0 ? currentIndex = $("#slider li")
.size() - 1 : currentIndex-- : currentIndex = n.attr("data-position");
What I can't wrap my head around is this code: currentIndex == $("#slider li").size() - 1?
If the currentIndex
of the slider is at the end of the list, then the highlighted dot navigation goes back to index position 0, but why does it determine this by checking the size, and then subtracting 1? Wouldn't it make sense to check if currentIndex
equals the result of .size()
? But when I remove the -1
the dot navigation, will disappear off the page, for however long the interval specifies, before showing up at poisition 0 again. If I change it to -2
the dot nav stops at the second to last point before it loops back around. Replacing .size()
with .length
does the same thing.
The reason why the -1
is there has been answered, but why does .size()
and .length
not work the way I think it should?
Upvotes: 2
Views: 55
Reputation: 3799
jQuery .size()
and .length
are not zero based because they are counting the number of elements in a list. So naturally, the counting would begin at 1. CurrentIndex is a zero based index probably because it's an index in an array. In an array of items, zero would be the first index/node and length-1 would be the last index/node.
Eg for posterity: 10 items in an array would look something like this:
item[0]
...
item[9]
While the size (or length) of the array is 10, the array index ranges from 0 to 9.
I'm not sure if this is what you're asking but it certainly seems to be.
Upvotes: 2