views:

1054

answers:

4
$(document).ready(function(){
        // The plugin
        $.fn.image = function(src, f){
        return this.each(function(){
                var i = new Image();
                        i.src = src;
                        i.onload = f;
                        this.appendChild(i);
                });
        }

        // The code for the image to load
  $("#asdf").image("images/3a.jpg",function(){
            alert("The image is loaded now");
        });     
});

ive found the above code. I want to have an element that can be loaded with an image, but before the image is fully loaded i want it to show a loading gif, (done this using css). It works but will show the image loading instead of waiting for it to be fully loaded. I think i should be showing the image where the alert is using hide() show() but im not quite sure how to reference it from inside the function?

+3  A: 

You might want to try using the Lazy Loader plugin (or a similar one) instead. Note that you can specify your own placeholder image.

tvanfosson
I removed my original answer as I missed that the image wasn't being replaced, but instead injected into a DIV. My answer wouldn't work in the later case.
tvanfosson
A: 

ive tried this with no luck, anyone see any problems>? i want to use the same div for the loading gif then the final image

$('#preload').replaceWith('<img src="preloader.gif" />')
          .image( "http://www.google.co.uk/intl/en_uk/images/logo.gif", function() {
             $('#preload').replaceWith( this );
             // is this called when image fully loaded?
          });
michael
$('#preload').replaceWith('<img src="preloader.gif" />') .image( "http://www.google.co.uk/intl/en_uk/images/logo.gif", function() { $('#preload').replaceWith( this ); // is this called when image fully loaded? });can you see any problems here
michael
A: 

You could try something like this:

    var $loadingImg = $('<img />').attr('id','loadingImg').attr('src','preloader.gif');
    $("#preload").html($loadingImg.html()).image("http://www.google.co.uk/intl/en_uk/images/logo.gif");

Do let me know how it goes.

karim79
A: 

found a plugin that does exactly what im looking, using a placeholder gif image untill the image is fully loaded then showing the final image

http://flesler.blogspot.com/2008/01/jquerypreload.html

michael