Adjusting the height of the Iframe dynamically every 2 seconds

One issue I am facing is with the iframe height. When I load the iframe, it sets the height correctly and adjusts when content is loaded dynamically. However, if I reduce or delete content from the loaded page, the iframe height does not decrease (e.g., initially set to 100px, dynamically increased to 150px, but remains at 150px even after reducing content). Here is the code snippet:

function setIframeHeight(iframe) {
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
        }
        setInterval("setIframeHeight_id('" + iframe.id + "')", 2000);
    }
    return false;
}

function setIframeHeight_id(iframeid) {
    var iframe = document.getElementById(iframeid);
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
        }
    }
    return false;
}

function resizeIframe(nm) {
    setIframeHeight(document.getElementById(nm));
}

HTML

 <iframe id="IframeData" scrolling="no" frameborder="0" width="100%" onload="resizeIframe('IframeData')" allowtransparency="true"></iframe>

Answer №1

My recommendation would be to opt for jQuery over plain JavaScript. While it may not work wonders on its own, incorporating jQuery can certainly assist in streamlining your code.

Regarding your issue, have you considered utilizing percentage sizes instead of fixed pixel dimensions? For instance, setting the height of your iframe to 100% rather than 150px. This way, if you adjust the size of the parent container in the future, the iframe will automatically adjust itself to match the parent's height.

I trust this solution proves helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Go back to the previous selection in the Select field if the JavaScript Confirm function returns a false value

I am dealing with an HTML select field that has one option pre-selected. Whenever another option is selected, a change event is triggered which displays a confirmation prompt. What I am trying to achieve is, if the user cancels the confirmation (i.e., if ...

What is the best way to bring in Javascript files to a specific component along with HTML and CSS?

` <script src="./jquery.min.js"></script> <script src="./bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="./jquery.easing.min.js"></script> <!-- Page level plugin JavaScr ...

What is the correct way to maintain focus on a nested scrolling div over another scrolling div with jQuery?

I have encountered an issue with a modal view that contains content extending beyond its boundaries. To remedy this, I applied the overflow-y: scroll property. However, the problem arises when the modal view overlaps with the body, which also has scrolling ...

Exploring the concepts of Html5 semantic elements

After spending years programming websites with HTML 4, I finally decided it was time to upgrade my skills and transition to HTML5. Unfortunately, older browsers don't support HTML5, but I discovered a JavaScript file called "html5shiv" that can help b ...

Upon refreshing the page, nested React routes may fail to display

When I navigate to the main routes and their nested routes, everything works fine. However, I encounter an issue specifically with the nested routes like /register. When I try to refresh the page, it comes up blank with no errors in the console. The main r ...

Implementing an alert box upon redirect with PHP

This question is pretty straightforward. I have a form on my index.html page and PHP code to submit that form to an external URL, then redirect back to the index: <?php Echo "<style>body{background:#3e4744}</style>"; Echo "<style>h2{ ...

Iterate through a nested array in JavaScript and extract specific properties by comparing them to another array

Within my code, there is a kids object structured as follows: const kids = { name: 'john', extra: { city: 'London', hobbies: [ { id: 'football', team: &apos ...

Deciphering Google location data using JavaScript

It appears that this code is not functioning properly for unknown reasons let url = "https://maps.googleapis.com/maps/api/place/search/json?"; url += "location="+lat+","+lng+"&"; url += "radius=500&"; url += "types=&"; url += "name=&"; url ...

breaking up various dates into specific formatting using React

I need to convert a series of dates Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC) into the format 11/13/2019, 11/19/2019, 11/19/2019 ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

I am unable to access the state after setting it in useEffect in React. Why is this happening?

After rendering the component, I utilize socket io to send a socket emit in order to fetch data within the useEffect hook. Subsequently, I also listen for the data that is returned. However, upon receiving the data back from the socket, I update the stat ...

Adding an external script to a Vue.js template

Delving into the world of Vue.js and web-pack, I opted to utilize the vue-cli (webpack) for scaffolding an initial application. A challenge arose when attempting to incorporate an external script (e.g <script src="...") in a template that isn't req ...

Delve into the world of tackling catastrophic backtracking with regex in Node

Currently, my node.js script includes this regex: const commentPattern = new RegExp( '(\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|(//.*)', 'g&a ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Validate whether the path parameter in NextJS is null or empty before executing the query

Currently seeking a method to determine if the query value is empty using the path parameter approach. Have a file named pages/search/[variable1].js Below is the code snippet: import { useRouter } from "next/router" const Variable= () => { ...

Double the names in a single <input>

Is it possible to assign two different names within a single input tag, like this: <input type='text' name='food' name='user_search_input'>? In my PHP file, I intend to use the input in two separate "if" clauses - one fo ...

Modifying the title of a webpage with a Bootstrap design

As a newcomer to HTML/CSS, I recently utilized a Bootstrap theme from Themezy to build my personal website. The template includes a navigation bar with tabs labeled Top, Work, Portfolio, and Contact. I felt the need to change Top to About, so I replaced ...

Issue with SVG mask not functioning when transform is applied

I am struggling to apply a mask to a transformed SVG element. When I try to do this with a path, the structure is the same. If I apply the mask to an element outside of the transformed group, it works as expected. However, if I try to do the same inside, t ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...