patternjavascriptMinor
Repositioning images in a gallery based on the current image
Viewed 0 times
gallerytheimagerepositioningbasedcurrentimages
Problem
I'm working on extending the functionality of a photo gallery by adding a thumbnail display, I have multiple if statements set up to adjust the position of the thumbnails. Obviously this is not ideal, I'm trying to put my head around how to use a for loop to iterate the width multiplier and curSlide position.
Ideally I would like the curSlide to increment after every 5 slide and the thumbGalwidth*i to increment as well.
Ideally I would like the curSlide to increment after every 5 slide and the thumbGalwidth*i to increment as well.
var thumbGalwidth = 795;
if(currSlide = 6) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*1 + 'px');
}
if (currSlide >= 11) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*2 + 'px');
}
if (currSlide >= 16) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*3 + 'px');
}
if (currSlide >= 21) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*4 + 'px');
}
if (currSlide >= 26) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*5 + 'px');
}Solution
Because you have nice, predictable ranges, you don't need a loop at all. Just do a little math.
If the largest
var thumbGalwidth = 795;
var n = Math.floor(((currSlide || 1)-1) / 5);
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*n + 'px');If the largest
n should be 5, then change the assignment to this:var n = Math.min(5, Math.floor(((currSlide || 1)-1) / 5));Code Snippets
var thumbGalwidth = 795;
var n = Math.floor(((currSlide || 1)-1) / 5);
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*n + 'px');var n = Math.min(5, Math.floor(((currSlide || 1)-1) / 5));Context
StackExchange Code Review Q#43007, answer score: 5
Revisions (0)
No revisions yet.