Reputation: 5757
I have 16 elements of the class row
I'm trying to change the elements that are showing at one time by slicing.
$(document).ready(function() {
$('.row').slice(0, 2).show();
$('.row').slice(3, 16).hide();
$('#next').click(function() {
$('.row').slice(0, 2).hide();
$('.row').slice(3, 5).show();
$('.row').slice(6, 15).hide();
});
});
So initially, you only see these three items:
Row 0
Row 1
Row 2
//$('.row').slice(0, 2).show(); -- this is correct
but then when I click my button to show the next three, instead this displays:
Row 2
Row 3
Row 4
//yet I specified this: $('.row').slice(3, 5).show();
Why does this happen and how could it be fixed?
Jfiddle: http://jsfiddle.net/RjHvw/
Upvotes: 0
Views: 3952
Reputation: 15861
slice method is based on zero based index, Slice, even end parameter also is based on zero-based. the range extends up to but not including the specified index.
Upvotes: 1
Reputation: 13461
As others have already said Slice uses 0 based index and the end numbered element is excluded from the selected list. Here is the argument definition in jQuery.com which says this
.slice( start [, end] )
startAn integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.endAn integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.
Here is working demo of what you are trying to achieve
Upvotes: 1
Reputation: 94121
Row 2
Row 3
Row 4
//yet I specified this: $('.row').slice(3, 5).show();
That seems correct, slice index is 0 based.
You can just add 1
:
// just so it's clear
// you'd tipically have an `idx`
// or `counter` where you add `1`
$('.row').slice(3 + 1, 5 + 1).show();
Upvotes: 1