I have an img
object that has NOT yet been appended to the document tree. Is it possible to assign an onclick event (using attachEvent
or addEventListener
) to that object? Or do I have to append it to the DOM first and only then would I be able to attach the event?
var image = document.createElement("img");
image.src = "image1.png";
// Will any of the following work?
image.attachEvent("onclick", displayImage); // IE
image.addEventListener("click", displayImage, false); // non-IE
document.getElementById("imageDiv").appendChild(image);
function displayImage() {
...
}
Please, only include pure JavaScript (no JQuery). Thank you!