views:

735

answers:

7

I am probably missing something simple but it's quite annoying when everything you read doesn't work. I have images which may be duplicated many times over the course of a dynamically generated page. So the obvious thing to do is to preload it and use that one variable as the source all the time.

var searchPic;
function LoadImages() {
    searchPic = new Image(100,100);
    searchPic.src = "XXXX/YYYY/search.png";
    // This is correct and the path is correct
}

then i set the image using

  document["pic1"].src = searchPic;

or

  $("#pic1").attr("src", searchPic);

however the image is never set propertly in FireBug when I query the image i get [object HTMLImageElement] as the src of the image

in IE I get

http://localhost:8080/work/Sandbox/jpmetrix/[object]

if anyone could help with this i'd really appreciate it

Thanks

John

+4  A: 

You should be setting the src using this:

document["pic1"].src = searchPic.src;

or

$("#pic1").attr("src", searchPic.src);
Richard
+1  A: 
document["pic1"].src = searchPic.src

should work

Nir Levy
A: 

You need to set

document["pic1"].src = searchPic.src;

The searchPic itself is your Image(), you need to read the src that you set.

Mat Mannion
+1  A: 

You don't need to construct a whole new image... the src attribute just takes a string value :-)

JorenB
If the page is generated dynamically using javascript, you'll want the image downloaded when the page is loaded so you don't get an annoying delay the first time you create an element that needs it. That's the reason for creating the Image object.
tvanfosson
You're right, I wasn't very precise in my answer. I just meant to say that the src attribute takes a string, and totally forgot about the caching advantage of creating the `Image` on beforehand. Thanks!
JorenB
A: 

instances of the image constructor are not meant to be used anywhere. You simply set the src, and the image preloads.. .and that's it, show's over. you discard the object and move on.

document["pic1"].src = "XXXX/YYYY/search.png";

is what you should be doing. You can still do the image constructor, and perform the second action in the onload handler of your searchpic. this ensures the image is laoded before yo uset the src on the real img object.

like so

function LoadImages() {
    searchPic = new Image();
    searchPic.onload=function () {
        document["pic1"].src = "XXXX/YYYY/search.png";
    }
    searchPic.src = "XXXX/YYYY/search.png"; // This is correct and the path is correct
}
Breton
A: 

Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.

Try

document["pic1"].src = searchPic.src;
Cory Larson
A: 

Wow! when you use src then src of searchPic must be used also.

ocument["pic1"].src = searchPic.src

looks better

Dewfy