What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js

Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scrollbars visible. Is there a way to remove the outer scrollbar and dynamically adjust the height of the HTML content to show only one scrollbar if needed?

Thank you!

import React, { useEffect } from "react";
import clsx from "clsx";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import Paper from "@material-ui/core/Paper";

const drawerWidth = 240; 

Answer №1

To ensure that the content fits properly within the outer div, adjust it vertically outside the iframe. You can try reducing the vh of the outer div for a better fit. Once the outer div is adjusted correctly to fit vertically, the outer scrollbar will disappear.

If you wish to hide the outer scrollbar forcefully, you can refer to this link

Answer №2

To solve this issue easily, adjust the full screen height for div#root by setting it to

style={{ height: "100vh" }}
and update the parent's height for the iframe as follows:

  <Paper elevation={1} style={{ height: "90%" }} flex={1} overflow="auto">
    <iframe
      id="widget"
      name="widget"
      title="widget"
      ...

You can view the codesandbox example through this link:

https://codesandbox.io/s/material-demo-forked-2gtyz?fontsize=14&hidenavigation=1&theme=dark

Answer №3

An iframe is unable to resize itself autonomously in order to prevent advertisers from enlarging their ads on web pages without permission.

Therefore, it is the responsibility of the parent element to determine and set the height of an iframe. One way to achieve this is by directly reading the content's height within the iframe and adjusting its height accordingly with the following approach:

const iframeRef = React.createRef();
const [iframeHeight, setIframeHeight] = React.useState('100%');

React.useEffect(() => {
  setIframeHeight(`${iframeRef.current.contentWindow.document.documentElement.scrollHeight}px`);
}, []);

const iframeRef = React.createRef();

<iframe
  ref={iframeRef}
  id="widget"
  name="widget"
  title="widget"
  scrolling="yes"
  frameBorder="0"
  width="100%"
  height={iframeHeight}
  srcdoc={html}
  style={{ position: "relative", height: iframeHeight }}
></iframe>

If the height of the iframe is subject to change due to asynchronous operations or user interactions, messages must be sent from the iframe to its parent using Window.postMessage when the height changes. These messages should include the updated height. Subsequently, an event listener for the message event needs to be added to the parent element to adjust the iframe's height accordingly.

Answer №4

When generating the HTML code, make sure to make adjustments in the <script> tag by adding the resizeIframe function and calling that function at the end of the document ready event:

        <script>
          function resizeIframe()
          {
            var document = window.parent.document;
            var iframe = document.getElementById('widget');
            iframe.style.height = (iframe.contentWindow.document.documentElement.scrollHeight + 18) + 'px';
          }

          var my_jquery = $.noConflict(true);
          my_jquery(document).ready(function(){
            my_jquery('#jEZeucEZQISp').DataTable({
              data: [["Alabama","Montgomery","https://en.wikipedia.org/wiki/Montgomery,_Alabama","TRUE"],["Alaska","Juneau","https://en.wikipedia.org/wiki/Juneau,_Alaska","TRUE"], ...],
              iDisplayLength:  25 ,
              "scrollX":      true,
              scrollY:        '',
              scrollCollapse:  false ,
              search: {
                search: "",
              },
            });
            resizeIframe();
            my_jquery(window.parent).on('resize', resizeIframe);
          });
        </script>

Afterwards, update your <IFRAME> tag as follows:

          <iframe
            id="widget"
            name="widget"
            title="widget"
            scrolling="auto"
            frameBorder="0"
            width="100%"
            srcDoc={html}
            style={{ position: "relative"}}
          ></iframe>

Check it on sandbox

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

Pausing a running function in React

Exploring Visual Sorting Algorithms In the process of creating a visual sorting algorithms tool for educational purposes, I have developed a function called sortArray() that handles the animation of the sorting process on arrays. The functionality is evid ...

Is it possible to transfer a specific feature from jQuery to Prototype?

I find myself in a situation where I have to use Prototype instead of jQuery, even though I'm not as familiar with it. Can anyone assist me in transforming the following script: var output={}; $$('ul li').each(function(item){ var firstL ...

Vue.js: click event does not trigger transform animation

I am facing a challenge with rotating an arrow icon within a dropdown menu. Despite my efforts, the rotation does not synchronize with the appearance of the dropdown menu. Here is the Vue component code snippet: <nav> <section class= ...

Having trouble unselecting the previous item when selecting a new item in Reactjs

I have a list of items and I want to change the background color of the currently selected item only. The previously selected item should deselect. However, at the moment, all items are changing when I click on each one. Can anyone help me solve this issue ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

"Mastering the art of event delegation: A guide to effectively engaging with various

I have data that is generated dynamically, as shown in the snippet below: const resultsDiv = document.getElementById("results"); const getList = document.getElementById("example"); document.querySelector(".container").addEventListener("click", function ...

Troubles with retrieving Array data for a JavaScript column chart

I am currently developing a Flask app in Python and utilizing render_template to send back 2 arrays, "names" and "deals", to my HTML file. I have confirmed that these arrays are working correctly based on the code snippet below that I tested, which display ...

Tracking mouse movement: calculating mouse coordinates in relation to parent element

I am facing an issue with a mousemove event listener that I have set up for a div. The purpose of this listener is to track the offset between the mouse and the top of the div using event.layerY. Within this main div, there is another nested div. The prob ...

Utilize Material-UI function by passing a function as an argument

I am currently using material UI in conjunction with React. I have a main component: import React, { Component } from 'react'; import CreateNewGarden from './CreateNewGarden'; const cookies = new Cookies(); class Dashboard extends Co ...

When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

Hovering over the child element, instead of the parent

I'm working on implementing a highlight feature for my website. The structure of the HTML looks something like this: <div> <!-- this is the main container --> <div> content ... </div><!-- a child element --> < ...

Steps to update the color of the asterisk in a mandatory field: How to change the

I am looking to change the color of the asterisk in my form fields from black to red. I am currently using the Material UI React library and need some guidance on how to achieve this. You can view the code here: https://codesandbox.io/s/r7lq1jnjl4 For mo ...

Aligning an SVG icon at the center of a button

I have elements that are currently being used as buttons, but I want to switch them out for actual button tags. This would improve accessibility and allow keyboard navigation using the tab key to focus on my buttons. Each button contains a centered SVG ima ...

Customizing Body Color in CKEditor for Dynamic Designs

I am facing an issue with CKEditor that I am hoping to find a solution for. My scenario involves using a jQuery color picker to set the background color of a DIV element, which is then edited by the user in CKEditor. However, I have observed that it is not ...

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Generate dynamic DIV elements and populate them with content

Can you assist me in getting this code to function properly? My goal is to dynamically create elements inside a div and fill each element with a value fetched from the database through a server-side function. I'm unsure if there's a better approa ...