tags:

views:

51

answers:

2

I am displaying a series of elements using the next() function. Once I reach the end though, I want to go to the first element. Any ideas?

Here's the code:

//Prev / Next Click
$('.nextSingle').click( function() {
    //Get the height of the next element
    var thisHeight = $(this).parent().parent().parent().next('.newsSingle').attr('rel');
    //Hide the current element
    $(this).parent().parent().parent()
        .animate({
            paddingBottom:'0px',
            top:'48px',
            height: '491px'
        }, 300) 
        //Get the next element and slide it in      
        .next('.newsSingle')
        .animate({
            top:'539px',
            height: thisHeight,
            paddingBottom:'100px'
        }, 300);
});

Basically I need an "if" statement that says "if there are no remaining 'next' elements, then find the first one.

Thanks!

+1  A: 

according to the jquery documentation, an empty jquery object will return of .length 0.

so what you need to do is check for the return when you call .next, and then call :first

http://api.jquery.com/next/

Oren Mazor
great... how do I do this?
j-man86
+3  A: 

Determine the .next() ahead of time by checking its length property.

$('.nextSingle').click( function() {
       // Cache the ancestor
    var $ancestor = $(this).parent().parent().parent();
       // Get the next .newsSingle
    var $next = $ancestor.next('.newsSingle');
       // If there wasn't a next one, go back to the first.
    if( $next.length == 0 ) {
        $next = $ancestor.prevAll('.newsSingle').last();;
    }

    //Get the height of the next element
    var thisHeight = $next.attr('rel');

    //Hide the current element
    $ancestor.animate({
            paddingBottom:'0px',
            top:'48px',
            height: '491px'
        }, 300);

        //Get the next element and slide it in      
    $next.animate({
            top:'539px',
            height: thisHeight,
            paddingBottom:'100px'
        }, 300);
});

By the way, you could replace .parent().parent().parent() with .closest('.newsSingle') (if your markup allows it).

EDIT: I corrected the thisHeight to use the $next element that we referenced.

patrick dw
thx patrick! Looks promising, but I get "Error: $ancestor.prevAll(".newsSingle").last is not a function"
j-man86
@j-man86 - What version of jQuery are you using? The `.last()` method was added in jQuery 1.4.
patrick dw
@j-man86 - Was just about to make an edit. I'll just leave a comment instead. If you need an older version of jQuery, then instead of `prevAll().last()`, you could do `.prevAll(':last')`.
patrick dw