View Full Version : Add onclick event from iframe

03-14-2009, 01:35 AM
I am trying to add an onclick event to a dynamically generated element. This happens in an iframe, but the element is being added to the parent document, and I need to associate the onclick event with a function in the parent document. When I add it from the iframe and then click on the image, I get an error saying the function does not exist.

var img = parent.document.createElement('img');
img.onclick = function() { doSomething() };
parentDiv.appendChild(img); //parentDiv is an element in the parent document

I also tried: img.setAttribute('onclick', 'doSomething(this);');
This worked great in Firefox, but not in IE.

03-18-2009, 06:08 PM
I couldn't figure out how to get this to work, so I ended up just moving the function to the parent document and calling it from the iframe: parent.addImageElement();