To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.
The src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.
To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.
You should be setting the src using this:
document["pic1"].src = searchPic.src;
or
$("#pic1").attr("src", searchPic.src);
img
tag and add attributes
manually ,var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src; // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);
pic1
document["#pic1"].src = searchPic.src;
or with getElementById
document.getElementById("pic1").src= searchPic.src;
$("#pic1").attr("src", searchPic.src);
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 can discard the object and move on.
document["pic1"].src = "XXXX/YYYY/search.png";
is what you should be doing. You can still use the image constructor, and perform the second action in the onload
handler of your searchPic
. This ensures the image is loaded before you set 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
}
Also, one way to solve this is to use document.createElement
and create your html img and set its attributes like this.
var image = document.createElement("img");
var imageParent = document.getElementById("Id of HTML element to append the img");
image.id = "Id";
image.className = "class";
image.src = searchPic.src;
imageParent.appendChild(image);
REMARK: One point is that Javascript community right now encourages developers to use document selectors such as querySelector
, getElementById
and getElementsByClassName
rather than document["pic1"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With