0

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!

Alex
  • 3,719
  • 7
  • 35
  • 57

2 Answers2

0

As far as I see you are searching for a native implementation of the jquery live()/on() functionality. You should take a look at Implementing jQuery's "live" binder with native Javascript.

Community
  • 1
  • 1
ju_
  • 569
  • 1
  • 4
  • 17
-1

what i found:

  1. add a judge before use it.
  2. getElementById's param needs a "#".
var image = document.createElement("img");
image.src = "image1.png";
if(image.attachEvent){
image.attachEvent("onclick", displayImage);} // IE

image.addEventListener("click", displayImage, false); // non-IE

document.getElementById("#imageDiv").appendChild(image);

function displayImage() {
  ...
}
张小咩
  • 9
  • 7