Определите .next()
заранее, проверив его свойство length
.
$('.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);
});
Кстати, вы можете заменить .parent().parent().parent()
на .closest('.newsSingle')
(если ваша разметка это позволяет).
РЕДАКТИРОВАТЬ: Я исправил thisHeight
, чтобы использовать элемент $next
, на который мы ссылались.