views:

63

answers:

2

I can't find this anywhere, how do you check to see if slice is returning elements still in the list? Like $('.class').slice(n-th,n-th);

When n-th variables are increased throughout the index of the return class by slicing, how do you know when slice returns on an invalid index? Hope I explained that well.

Here is the example code of what I'm trying to accomplish:

$(window).scroll(function() {
    if(!($('embed').slice(p1,p2).show())){
        $(window).unbind('scroll');
    }
    ++p1;++p2;
}

Also, why is my event not unbinding?

Thanks for any assistance :)

+1  A: 

Simply test slice().length to see if you got anything back, or you can test it for a specific length.

In your case:

var $mySlice = $('embed').slice(p1,p2); // <== Store slice

  // Check that slice returned 1+ elements
if( $mySlice.length ) { 

      // show them if yes
    $mySlice.show();
} else {

      // unbind if no
    $(window).unbind('scroll');
}

In general you want to look at:

$( ... ).slice( ... ).length

The above simply tests for 1+ elements. If you're slicing off N elements and you want to make sure that you get a full and complete result, simply modify to

if ( $mySlice.length == N ) {

jQuery's .slice() never returns things beyond the end of the remaining elements. It's smart enough to know when to stop.

If you give it an end point that exceeds the number of elements, it'll return the elements that exist, then it'll stop without a runtime error.

Peter Ajtai
It does return an empty jQuery object, which will evaluate to true for the code he gave above, so that's not really helpful. Should be evaluating the `length` property instead.
Yi Jiang
+1 just for the effort ;)
no
@Yi Jiang - Of course. Thanks. Didn't quite get the question at first.
Peter Ajtai
@no - Thanks - I think I actually fixed it to answer the question ;)
Peter Ajtai
Thanks, answered my question and worked (checked it with firebug). :) Very much appreciated.
@user455046 - You're welcome ;)
Peter Ajtai
A: 

Slice just returns an empty array if you pass it bad arguments.

no
The array is not empty. It includes the part "that makes sense". If there are 5 elements and you `jQuery(...).slice(0,999)` you will get an array of 5 elements, not an empty array.
Peter Ajtai
Good point.....
no