How to make <iframes> load only on a button click?

Member

by denis , in category: Third Party Scripts , 23 days ago

How to make <iframes> load only on a button click?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 23 days ago

@denis 

You can achieve this using JavaScript. Here's a step-by-step guide:

  1. Create an iframe element in your HTML code with a unique ID:
1
<iframe id="myFrame" src="https://www.example.com"></iframe>


  1. Add a button to your HTML code with an onclick event handler that triggers the loading of the iframe:
1
<button onclick="loadIframe()">Load Iframe</button>


  1. Add a JavaScript function that will load the iframe when the button is clicked and hide the iframe initially:
1
2
3
4
5
function loadIframe() {
  var iframe = document.getElementById("myFrame");
  iframe.style.display = "block";
  iframe.src = "https://www.example.com";
}


  1. Optionally, you can also add CSS to hide the iframe initially:
1
2
3
#iframe {
  display: none;
}


Now, the iframe will only load when the button is clicked.