Javascript set img src

John picture John · Aug 5, 2009 · Viewed 361.5k times · Source

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 properly 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]

Answer

Richard picture Richard · Aug 5, 2009

You should be setting the src using this:

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

or

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