tags:

views:

700

answers:

4

Hello,

I new to JQuery and I am trying to do a proof-of-concept with it. I am trying to use JQuery to: 1) Download a large (>500kb) image file 2) Set the image as the background of an element when downloaded 3) fade it in (basically the way that Bing.com does it). The StackOverflow community has generously helped me most of the way through this problem as shown here. However, I still have one problem that I cannot figure out.

How do I make the downloaded image the background-image of an HTML element? The code that I see at http://jqueryfordesigners.com/image-loading/ appends an image element to a DIV. However, I want to set the image as the background-image of a DIV once downloaded and fade it in. Is this possible? I seem to keep going around in circles on this. Thank you.

A: 

Assuming you're using the browser to download the image, once you have it, it's in the browser's cache. Setting the background image of the DIV to the URL of the image should not download it a second time, but rather just load it from the cache. Then you can discard your image object.

However, I don't know of a way to apply transitional effects to CSS background images. If the fading in is a hard requirement, you may be better off setting the background color of your DIV to transparent, and absolutely positioning your image element behind the DIV. Then you can fade it in using ordinary jQuery techniques.

Joel Mueller
A: 

Actually, all you have to do is something like

$("#myDiv").css({background-image: "url('http://someserver.com/someImage.jpg')"})

You can completely skip the 'downloading' part, since the browser will take care of that.

chris166
As I understood the question, Villager wants to have fancy fade-in effect when image finally loads. And probably the spinning "loading..." animation, too.
drdaeman
Ah, I get it. Anyway, a better answer has already been posted by drdaeman
chris166
+3  A: 

Put additional div (with width: 100%; height: 100%) in #loader: <div id="loader"><div class="image"></div></div>.

Then, instead of $("#loader").append(this); you should to something like $("#loader div.image").css("background","url(images/headshot.jpg) no-repeat 0 0");. This way the img element will stay invisible out of the document tree, but background — hopefully cached, at least most browsers will do so — will be shown in your div.

Then, finally, do effects on your inner div with .fadeIn().

Haven't tried this by myself, but it must be something like this.

drdaeman
A: 

As I said in my answer to that question. After downloading it is in the cache, so it won't be downloaded a second time.

Pim Jager