Loading a gallery of external images with JQuery

Posted by pingu on Stack Overflow See other posts from Stack Overflow or by pingu
Published on 2010-04-26T10:16:36Z Indexed on 2010/04/26 10:23 UTC
Read the original article Hit count: 257

Filed under:

Hi guys, I'm creating a gallery of images pulled in via a twitter image hosting service, and I want to show a loading graphic before they are displayed, but the logic seems to be failing me. I'm trying to do it the following way:

<ul>
    <li>
        <div class="holder loading">
        </div>
    </li>
    <li>
        <div class="holder loading">
        </div>
    </li>
    <li>...</li>
    <li>...</li>
</ul>

Where there "loading" class has an animated spinner set as it's background image.

JQuery:

$('.holder').each(function(){
    var imgsrc = http://example.com/imgsrc;
var img = new Image();
    $(img).load(function () {
        $(this).hide();
        $(this).parent('.holder').removeClass('loading');
        $(this).parent().append(this);
        $(this).fadeIn();
})
.error(function () {
}).attr('src', imgsrc);
 });

Which isn't working - I'm not sure that the logic is correct and how to access the "holder" from inside the img.load nested function. What would be the best way to build this gallery so that the images display only after they've been loaded?

© Stack Overflow or respective owner

Related posts about jQuery