I've been working on a JavaScript function that dynamically generates an iframe with a button that, when clicked, deletes the iframe itself.
Here are the functions I've written:
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 issue I'm facing is that the onclick function of the button executes immediately without user interaction, leading to the immediate deletion of the newly created iframe. How can I resolve this problem?
Additionally, is there a way to place the button inside the new iframe instead of directly in the parent body?
Thank you for any help you can provide in advance.