The best way to write this code? Jquery
Ive got an array which I am doing a few things, but now I am trying to split it between "pages" (more like slides).
I am going through it with a method .each()
, calling this long bit of code to put the information on the correct page (only 5 elements per page, at least for now).
Is there a way to simplify this code?
Ideally, this could go on indefinitely:
if (index > 0 && index <= 5) {
var page = $('#librarian-page-gallery-1');
} else if (index > 5 && index <= 10) {
var page = $('#librarian-page-gallery-2');
} else if (index > 10 && index <= 15) {
var page = $('#librarian-page-gallery-3');
} else if (index > 15 && index <= 20) {
var page = $('#librarian-page-gallery-4');
} else if (index > 20 && index <= 25) {
var page = $('#librarian-page-gallery-5');
} else if (index > 25 && index <= 30) {
var page = $('#librarian-page-gallery-6');
} else if (index > 30 && index <= 35) {
var page = $('#librarian-page-gallery-7');
} else if (index > 35 && index <= 40) {
var page = $('#librarian-page-gallery-8');
} else if (index > 45 && index <= 50) {
var page = $('#librarian-page-gallery-9');
}
+3
rpsep2
source
to share
1 answer
For example:
var page = $('#librarian-page-gallery-' + Math.ceil(index/5));
Explanation:
index/5 builds a float number :
1 -> 0.2
4 -> 0.8
5 -> 1
6 -> 1.2
and Math.ceil returns the nearest greater or equal integer :
0.2 -> 1
0.8 -> 1
1 -> 1
1.2 -> 2
+5
Denys Sรฉguret
source
to share