Reputation: 7519
I had asked this question a few weeks back on how to preload images in a gallery. While the solution works, the issue that arises now is that if I click on Next to preload the next three images and there are only two images ahead, it runs the loop all three times and Firebug throws an undefined error.
This is the code:
$('#next').bind('click',function(){
var $this = $(this);
var $nextimage = $('#content img:nth-child('+parseInt(current+2)+')');
var next = $nextimage.next();
for (var i = 0; i < 3; i++)
{
var img = new Image();
img.src = next.attr("alt");
next = next.next();
}
navigate($nextimage,'right');
});
How do I catch the undefined
error, that if there are only 2 or 1 images, it should preload only those images and not run the loop the third or second time to throw the error?
Upvotes: 0
Views: 488
Reputation: 47099
$('#next').bind('click',function(){
var $this = $(this);
var $nextimage = $('#content img:nth-child('+parseInt(current+2)+')');
var next = $nextimage.next();
for (var i = 0; i < 3; i++)
{
if ( !next.length ) break; // This line stops your loop if there isn't any next
var img = new Image();
img.src = next.attr("alt");
next = next.next();
}
navigate($nextimage,'right');
});
EDIT:
Maybe you have next element in the DOM but not with the attribute "alt":
$('#next').bind('click',function() {
var $this = $(this),
$nextimage = $('#content img:nth-child('+parseInt(current+2)+')'),
$next = $nextimage.next();
for (var i = 0; i < 3; i++) {
if ( !$next.length ) break; // This line stops your loop if there isn't any next
var img = new Image();
img.src = next.attr("alt");
$next = $next.next("[alt]"); // Only takes elements with the alt attribute.
}
navigate( $nextimage, 'right' );
});
Upvotes: 2