How to auto-size an iFrame
javascripthtmlTo auto-size an iframe to fit its content, you can use the offsetHeight and offsetWidth properties of the iframe element to get the height and width of the content, and then set the height and width attributes of the iframe element accordingly.
Here is an example of how you can do this using JavaScript:
const iframe = document.getElementById('my-iframe');
// get the height and width of the content
const height = iframe.contentWindow.document.body.offsetHeight;
const width = iframe.contentWindow.document.body.offsetWidth;
// set the height and width of the iframe
iframe.setAttribute('height', height);
iframe.setAttribute('width', width);
You can also use the scrollHeight and scrollWidth properties to get the full height and width of the content, including any scrollbars.
const iframe = document.getElementById('my-iframe');
// get the height and width of the content, including scrollbars
const height = iframe.contentWindow.document.body.scrollHeight;
const width = iframe.contentWindow.document.body.scrollWidth;
// set the height and width of the iframe
iframe.setAttribute('height', height);
iframe.setAttribute('width', width);
You can use this code in a function and call it whenever the content of the iframe changes, or you can use the load event of the iframe element to call the function when the content finishes loading.
iframe.addEventListener('load', function() {
// get the height and width of the content
const height = iframe.contentWindow.document.body.offsetHeight;
const width = iframe.contentWindow.document.body.offsetWidth;
// set the height and width of the iframe
iframe.setAttribute('height', height);
iframe.setAttribute('width', width);
});
Keep in mind that this will only work if the content of the iframe is on the same domain as the parent page. If the content is on a different
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame
Other Article on Tag html
- - convert HTML to XHTML
- - dynamically create html element in javascript
- - How to auto-size an iFrame
- - How to use google image url as src for image
- - .htm vs .html what is different?
- - HTML CSS insert line breaks in HTML documents
- - html css Remove border from IFrame
- - HTML Landscape printing
- - html layout
- - html textarea no change size