Modifying the CSS attributes within an iframe by referencing the parent window's properties

I am facing a challenge involving running an iframe on two separate pages within the same website, each with distinct CSS properties. The dilemma arises from the limited space available on my index.php page, where I aim to confine text within the iframe to a narrow width. Conversely, on another page (samples/index.php), there are no limitations in terms of width, allowing for a larger iframe display. If I were to employ the same "large" width setting on both pages and adjust the iframe to be narrower on index.php, the text would extend beyond the edge and become obscured (without utilizing scrollbars).

In index.php, the declaration is as follows:

<iframe id="iframe_1" src="samples/data-iframe.html" width="850px" scrolling="no"></iframe>

On samples/index.php, the width is set to be narrower:

<iframe id="iframe_2" src="data-iframe.html" width="620px" scrolling="no"></iframe>

The linked data-iframe.html file outlines the following CSS styling:

<style type="text/css">

#gallery { position: relative; width:500px; height:340px; margin:0; padding:0; }
#gallery li { display: block; }

p.blocktext {
margin-left: auto;
margin-right: auto;
width: 800px;
font-size:11px;
color: black;
background-color: white;
}

#everything {
border-style:double;
border-width:3px;
margin-left: auto;
margin-right: auto;
width: 830px;
background-color: white;
}
#everything hr { width:600px; }

</style>

This CSS snippet encapsulates all elements within a div with a width of 830 pixels, enclosed by a double-lined border, and restricts the text content to an area of 800px.

The actual content displayed via the iframe is sourced from an external JavaScript file - immediately subsequent to the CSS declarations:

<script src="samples/test-iframe.js"></script>

Within test-iframe.js, we find examples such as:

document.write("<center>");
document.write("<div id=\"everything\">");
document.write("<ul id=\"gallery\">"); 
document.write("<li><img src=\"photo1.jpg\" alt=\"\" /></li>");
document.write("<li><img src=\"photo2.jpg\" alt=\"\" /></li>");
document.write("<li><img src=\"photo3.jpg\" alt=\"\" /></li>");
document.write("<li><img src=\"photo4.jpg\" alt=\"\" /></li>");
document.write("<li><img src=\"photo5.jpg\" alt=\"\" /></li>");
document.write("</ul>");
document.write("<p class=\"blocktext\">Dummy text.</p><hr><p class=\"blocktext\">More Dummy text (Note the hr to separate the two portions of text)</p></div>");
document.write("</center>");

All images have been resized to fit within the large iframe on index.php and the smaller one on samples/index.php. It is possible that the textual content may be extensive - the provided text serves as a placeholder and is confined within a smaller area.

My attempt involves using the code below to determine the parent window - if it contains "samples", then display the full width of the text, otherwise use a restricted width:

var str = parent.location.href;
var nt = str.indexOf("samples");

var a = document.getElementById("blocktext");
var b = document.getElementById("everything");

if (nt>0) // 'samples' found  
{
a.style.width = "800px";
b.style.width = "830px";
b.style.hr = "600px";
}
else // 'samples' not found - utilize narrower dimensions
{
a.style.width = "500px";  
b.style.width = "600px";  
b.style.hr = "400px"; 
}

Despite properly determining the parent window through testing, the CSS adjustments do not seem to take effect. Upon experimenting with additional code within the if blocks, it appears that while the script correctly identifies the parent window, the widths and hr properties remain unchanged. Can someone deduce what might be causing this discrepancy?

Answer №1

Utilizing CSS @media queries is a more efficient approach than using JavaScript to ensure your content is well-fitted:

p.blocktext {
margin-left: auto;
margin-right: auto;
width: 800px;
font-size:11px;
color: black;
background-color: white;
}

#everything {
border-style:double;
border-width:3px;
margin-left: auto;
margin-right: auto;
width: 830px;
background-color: white;
}
#everything hr { width:600px; }

@media all and (max-width: 829px) {
    p.blocktext {
        width: 500px;
    }
    #everything {
        width: 600px;
    }
    #everything hr {
       width: 400px;
    }
}

However, it is considered best practice to design with responsive sizes.

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

Create a PDF document with a custom header and footer by converting an HTML template using itext7

I attempted to utilize the following HTML template in an effort to convert it to a PDF using iText7, however, I am facing an issue where both the header and footer are not aligning to their designated positions. You can view the example I used here. I am s ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...

Enhance the size of dynamically generated svg elements by scrolling the mouse wheel in and out

In my ASP.NET application, I have a view page where SVG elements are dynamically generated. Now, I want to implement zoom functionality for all the created SVG elements. Zooming in should occur when scrolling up and zooming out when scrolling down. <sv ...

Issue with box-sizing border-box not applying to top and bottom borders

Currently, I am in the process of developing my own responsive website. However, I have encountered an issue with the box-sizing border-box on the top and bottom borders of one specific image. The layout consists of two columns with images of varying heigh ...

Navigating through drop-down menus using jQuery

I need help with a JavaScript script that can calculate the total number of points based on selected checkboxes and dropdown values. Currently, my script is able to iterate through checkboxes and assign 1 or 2 points based on their classes, but I'm st ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Invoking a Jquery function through a GridView link

After attempting various methods for hours, I am throwing in the towel. It's possible that someone here might spot what I'm missing. I have a GridView containing a Delete button. Upon clicking on the ClientClick event, a javascript function is in ...

What are some ways to implement a pre-execution step, such as an interceptor, before Nextjs runs getStatic

When working with getStaticProps and getServerSideProps in Next.js, I need to intercept and add common header properties to all request calls that are executed server-side. axios.interceptors.request.use(function (config) { // Perform actions before ...

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

Trigger an immediate repaint of a DOM element in the browser

Searching for a way to insert a large HTML markup into a DOM element that will take some time. This is why there's a need to display a preloader indicator before the process begins. Two blocks are involved: #preloader and #container. Initially, the pr ...

What is the proper way to address the issue of nesting ternary expressions when it comes to conditionally rendering components?

When using the code below, eslint detects errors: {authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />} Error: Avoid nesting ternary expressions. eslint(no-nested-t ...

Completely triggering a forced refresh on a single page application, disregarding cache, service workers, and all other

After experimenting with service workers on my Vue-built website, I made a critical error that has left Safari on my iPhone displaying only a blank page. To troubleshoot the issue, I connected my phone to my Mac and utilized Safari's inspector tool t ...

Error caused by the shouldDisableDate prop in MUI DatePicker's functionality

<Controller name="toDate" control={control} defaultValue={null} render={({ field }) => ( <DatePicker format="DD/MM/yyyy" value={field.value} onChange={(e) => { setToDate(e); field.onC ...

Adjust the width of a div element automatically using CSS

I have a dropdown bar with various options that I want to display inline while ensuring they can scale to occupy the entire width of the div, allowing for multiple options per row. Below is a screenshot showing my current progress: https://i.sstatic.net/3 ...

Is there a way to deactivate specific options within the "Select" component on Material-UI, similar to how it is done in the "Autocomplete" feature?

Is it possible to restrict certain options in the Select component similar to how it is done in the Autocomplete component? PS: The options are present in an array. <FormControl variant="outlined"> <InputLabel>States</Inp ...

Utilizing Java in JSP to execute jQuery functionality through a hyperlink

Working on a project with my school group and encountering some difficulties... We have a table in which we are using JSP to populate with data through a for-loop. Each cell in the table represents an object utilizing JPA with its own unique id. In our ...

Impact on adjacent div

Within my code, I have two sibling divs that contain additional nested divs as shown below: <div class="btn_lists"> <div class="btn green_btn"> <img src="<?= asset_url() ?>images/escolar_07__1.png" /> </div> & ...

Tips for managing an interval for play, pause, and stop functions in JavaScript or Node.js

In my main file, I have an API to control the playback of a video. main.js const { mainModule } = require('process'); const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js'); function init(payload) { if(payl ...

Once the user clicks on the download button, the backend should initiate the download process

I am seeking a solution where a download can be triggered in the background when a download button is clicked, without interrupting other tasks. Is there a way to achieve this in PHP? If so, what method can be used? I have attempted using the curl function ...