I got this code from Jquery in Action:
$.fn.photoslide = function(options) {
var settings = $.extend({
photoElement:'img.photoslidePhoto',
transformer:function(name) {
return name.replace(/thumbnail/,'photo');
},
nextControl:null,
previousControl:null,
firstControl:null,
lastControl:null,
playControl:null,
delay:3000
},options||{});
$(settings.previousControl)
.click(function() {
showPhoto((settings.thumbnails$.length + settings.current - 1)
% settings.thumbnails$.length);
}); //Why not just use settings.current - 1??
the code is meant to be used with a slider. The slider has a button that displays the previous photo.
This is the code for the showPhoto() function:
function showPhoto(index) {
$(settings.photoElement).attr('src',settings.transformer(settings.thumbnails$[index].src));
settings.current = index;
};
settings.thumbnail$
.each(function(n) {
$(this).data('photo-index',n);
})
.click(function() {
showPhoto($(this).data('photo-index'));
});
My question is, why can’t the index argument for showPhoto() in the click event for $(settings.previousControl) be defined simply as settings.current - 1?
I know this is a long post, but I would appreciate it very much if someone could help me understand this.
settings.thumbnails$.lengthis added to avoid negative indexes.If it was not added and
settings.currentis0, the result would be-1. Important to know is that applying the modulus in JavaScript does not make the number positive (unlike in other languages like Python):It would stay
-1which eventually would result in an error if you try to access an array with it.Adding
settings.thumbnails$.lengthguarantees the number to be positive but does not change the result (as it is zero in the context of the modulus operator).In case you wondered what the modulus operator [Wikipedia] is for: I assume this is used to show the photos in a loop.