How to update an iframe with javascript?

Member

by brandy , in category: HTML & CSS , 8 months ago

How to update an iframe with javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 6 months ago

@brandy 

To update an iframe using JavaScript, you can target the iframe element by its ID and then change its source attribute to the new URL you want to load. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
  <title>Update Iframe with JavaScript</title>
</head>
<body>

<iframe id="myIframe" width="500" height="300" src="https://www.example.com"></iframe>

<button onclick="updateIframe()">Update Iframe</button>

<script>
function updateIframe() {
  var iframe = document.getElementById('myIframe');
  iframe.src = 'https://www.newexample.com';
}
</script>

</body>
</html>


In this example, we have an iframe with the ID "myIframe" and a button that calls the updateIframe() function when clicked. Inside the function, we target the iframe by its ID, and then update its src attribute to 'https://www.newexample.com'.


When the button is clicked, the iframe will be updated to display the new URL.

Related Threads:

How to update chart.js using javascript?
How to run a javascript event on shopify cart update?
How to update the height of the iframe?
How to update iframe in vue.js?
How to disable iframe from javascript?
How to run a javascript code over an iframe?