I’m writing a javascript function that dynamically creates an Iframe with a button that if pressed can delete its iframe.
These are my javascript functions:
function createIframe (iframeName, width, height) {
var iframe;
if (document.createElement && (iframe = document.createElement('iframe'))) {
iframe.name = iframe.id = iframeName;
iframe.width = width;
iframe.height = height;
var connectIP = document.getElementById("ip").value;
var connectPORT = document.getElementById("port").value;
iframe.src = "http://"+connectIP+":"+connectPORT;
document.body.appendChild(iframe);
addElement(iframe.name);
}
return iframe;
}
function removeIframe(iframeName) {
iframe = document.getElementById(iframeName);
if (iframe) {
var x=iframe.parentNode.removeChild(iframe)
}
}
function addElement(iframeName) {
var butt = document.createElement('button');
var butt_text = document.createTextNode('Remove');
butt.appendChild(butt_text);
butt.onclick = removeIframe(iframeName);
document.body.appendChild(butt);
}
The problem is that, when the button is created, the onclick function is executed immediately and not only when the user presses it, so my new Iframe is immediately deleted and I cannot see it.
How can I solve this problem?
Moreover, is it possible to add the button not in the parent body but directly into the new created iframe?
Thanks in advance.
The onclick has to be a function, replace following line
with