Reputation: 141
I have a code that asks a user to input a URL and append it to a div using javascript and it works fine. what I was trying to add was editing the user entered URL, specifically change the width and height of the iframe entered by the user then appending it. My current code is attached below. Any help is appreciated. Thanks in advance.
function input() {
globalThis.urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
document.getElementById("add_to_me").innerHTML += urlInput;
document.getElementsByTagName('iframe').width= "300px";
document.getElementsByTagName('iframe').height= "300px";
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
Upvotes: 1
Views: 153
Reputation: 1
I think this is what you're trying to do;
function input() {
globalThis.urlInput="";
urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src",urlInput );
ifrm.style.width = "300px";
ifrm.style.height = "300px";
ifrm.style.frameborder = "0";
ifrm.allowFullScreen = true;
document.body.appendChild(ifrm);
}
<button onclick="input()">Input</button>
Upvotes: 4
Reputation: 852
Basically what I do is I create the iframes dynamically and prompt multiple times for url, width and height which I then set on the newly created iframe DOM-Element.
As far as I know it is generally considered bad practice to use global variables. So I edited your code to inject the user input from user function input()
into
appendiFrame(input)
.
Here's my extended code (consider the comments):
function input() {
// create local variable
var input = { url: '', width: '0', height: '0'} // creates dictionary containing input
input.url = prompt("Enter embed URL:")
if ( input.url == "") { // test if url was given
alert("No URL Inputted")
return // return if empty
}
input.width = prompt("Enter width:")
input.height = prompt("Enter height:")
appendiFrame(input)
}
function appendiFrame(input){
iframe = document.createElement('iframe') // create iframe dynamically
iframe.src = input.url;
iframe.width= input.width
iframe.height= input.height
document.getElementById('add_to_me').appendChild(iframe)
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
In order to test it you need to also enter the protocol (https
) as part of the url. The site also must not send the X-Frame-Options: sameorigin
HTTP-header as e.g. Google does or else your browser won't load the iframe.
You might also perform some checking whether the inputs entered are valid.
Upvotes: 1