views:

23

answers:

2

hi all,,

i'm trying to make a simple image-preloader for just ONE image. it should load an image and - if finished - fire an event for displaying it. what's the simplest method to do this?

i only know the pure javascript solution, like document.createElement("img") - but what's the best method using jquery?

what i've got so far (but dunno if it's the optimal way):

var img = $("<img src='/images/myPic.jpg'>");
img.bind("load", function(){alert("loaded!")});

thanks

+2  A: 

If I understand correctly I would write the image in the template or master page or whatever using with a css attribute and then an event in jquery to display it.

<img id="preloader" src="/myimg.jpg" style="display:none;" />


$("#some-element").ready(function(){
      $("#preloader").show();
});
Justin Soliz
+1  A: 

I've never had to do this with jQuery as I either do it manually in JS:

var img = new Image();
img.onLoad = function() {alert("Image has been loaded!");};
img.src = "path/to/img.ext";

Or, if I'm already using jQuery for the project, I'll just use Thickbox. If you look at its source, it has something similar to the above.

To display it, have a pre-defined div in your source file that is initially set to display: none;, then use JS to set its content to the image and change it to be visible. You can see an example of this at pcgalore.com, the rotating quote banner uses it.

ReK_