0

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?

Community
  • 1
  • 1
input
  • 7,503
  • 25
  • 93
  • 150

1 Answers1

2
$('#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' );
});
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • I don't know why but it still is throwing the undefined error. Chrome debugger shows at this line: `img.src = next.attr("alt");` – input Jan 02 '12 at 17:30