kmunky
kmunky

Reputation: 15583

jquery preload images

ok, so i have this "slideshow.html" containing just a bunch of pictures, and the "index.html".

index.html

<a href="">click</a>
<ul></ul>

slideshow.html

<li><img src="1.jpg" alt="" /></li>
<li><img src="2.jpg" alt="" /></li>
<li><img src="3.jpg" alt="" /></li>

and i have my script like this;

$(document).ready(function(){
            $('a').click(function(){
            $('ul').append('<li id="preloader"><img src="preLoader.gif" /></li>');
                   $('ul').load('slideshow.html',function(){
                           $('#preloader').remove();
                   });
            });
});

so i want on click to append the preloader.gif and to call the load method and after the images form the slideshow.html are loaded to remove the animation. Using my script it won;t do the thing, the page is loaded but the animation is dropped before the image is completely loaded :( thanks

Upvotes: 0

Views: 3692

Answers (2)

kmunky
kmunky

Reputation: 15583

$(document).ready(function(){
    //anchor click
$('a').click(function(){
    //empty the div
    $('div').empty();
            //perform ajax request
    $('div').load('toLoad.html',function(){
                  //hides all loaded images
        $('div.imageHolder img').hide();
                  //applies preloader for each image loaded
        $('div.imageHolder img').each(function(){
            //creates new image object
            var img = new Image();
                            //the current image src is stored in sursa variable
            var sursa = $(this).attr('src');
                            //the current image parent is stored in parent var 
            var parent = $(this).parent();
                            //the load animation is appended to current image parent 
            parent.append('<img src="blueLoader.gif" alt="loader" />');
           //loading image css settings
            $('img[alt="loader"]').css({'display':'block','margin':'10px auto'});
                           //this is the key
            $(img).load(function(){
                            //after image is loaded
                parent.append($(this));
                $(this).hide().fadeIn(500).css({'width':'200px','height':'80px'});
                $(this).siblings().remove();
            }).attr('src',sursa);


        });

    });
    return false;
}); 
   });

Upvotes: 2

keithm
keithm

Reputation: 2813

Preloading images is done differently than this. In jQuery it can be done something like this (untested):

$('<ul><li id="image1"><img id="throbber1" scr="preLoader.gif" /></li></ul>').appendTo('body');
var $img = $(new Image()).attr('src', '1.jpg').appendTo('ul li#image1');
$img.load(function() {
    $('#throbber1').hide();
});

Upvotes: 0

Related Questions