Is there a way to attach an event handler like onclick=alert(“Hi”); to an existing document element? (an image in my case)
I have already tried and failed with the following:
img = document.getElementById("my_image");
img.onclick = "alert('hi')";
img.setAttribute ('onclick',"alert('hi')");
img.onclick = function() {"alert('hi')";};
img.onclick = function(evt) {"alert('hi')";};
img.setAttribute ('onclick',function() {"alert('hi')";});
function handler(evt) {"alert('hi')";}
img.onclick = handler;
I am running out of ideas. Does anybody know how to do this?
The first answer by zzandy should be fine. Check you are doing everything correctly especially firefox can be choosy about ensuring it is in complient mode. Here is the full code.