Adjusting the size of the iframe on-the-fly

Scenario: Currently, I am tackling a project involving developing a responsive design using the standard HTML/CSS combination. Everything seems to be working smoothly except for one specific situation where an iframe is nested inside a div. The challenge lies in making sure that the iframe adjusts its size automatically based on the dimensions of its parent div. Despite exploring purely CSS solutions, I have resorted to utilizing jQuery to address this issue. While this method works well overall, there is a particular scenario in which it falters – when transitioning from a narrower screen width to a wider one.

Markup (HTML):

<div class="container">
    <iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>

Styling (CSS):

.container {
    width: 100%;
    height: 250px;
}
.iframe-class {
    width: 100%;
    height: 100%;
    border: 1px solid red;
    overflow: auto;
}

Scripting (JavaScript):

$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var originalWidth = 700;
    var originalHeight = 600;
    var originalRatio = originalWidth / originalHeight;

    var windowWidth = $(window).width();
    if (windowWidth < 480) {
        var parentDivWidth = $(".iframe-class").parent().width();
        var newHeight = (parentDivWidth / originalRatio);
        $(".iframe-class").addClass("iframe-class-resize");
        $(".iframe-class-resize").css("width", parentDivWidth);
        $(".iframe-class-resize").css("height", newHeight);
    } else {
        // $(".iframe-class-resize").removeAttr("width");
        // $(".iframe-class-resize").removeAttr("height");
        $(".iframe-class").removeClass("iframe-class-resize");
    }
}

Here is the demo link for reference.

Challenge: The primary issue arises during the resizing process, especially when the window width dips below 480 pixels. At this point, the code applies a class named iframe-class-resize and sets specific width and height values. However, upon expanding the window beyond 480 pixels, removing the class does not revert the iframe back to its original dimensions. Attempts to remove the added attributes using removeAttr() have proven ineffective.

If anyone can spot the flaw in the provided code or offer alternative strategies for achieving a more efficient responsive iframe solution, feel free to provide insights. It is crucial to maintain the relationship between the iframe and its parent <div></div>, even if the latter does not always contain predefined dimensions. Ideally, the parent div should have explicit width and height properties, but flexibility is necessary given the current site configuration.

Further Details: For clarity on the issue described above, follow these steps to reproduce the problem:

  • Access the provided jsfiddle link in a non-maximized desktop browser, preferably Chrome on Windows.
  • Observe how the iframe content fills the Preview panel's width completely.
  • Manually decrease the window width until it falls below 480 pixels, resulting in a visibly smaller iframe content.
  • Gradually increase the window width back up past 480 pixels, aiming to restore the iframe content to its initial full width within the Preview panel. Instead, you will notice that the content retains the altered size due to the direct application of CSS changes via the .css() function directly to elements rather than classes.

Your assistance is highly appreciated!

Answer №1

You only need 30 characters to make this change:

$(".iframe-class").removeClass("iframe-class-resize").css({ width : '', height : '' })

This code will reset the width and height that were previously applied to the element. Using .css() adds the passed-in values to the style attribute of the element. Passing a blank value removes that property from the style attribute.

Check out the updated fiddle here: http://jsfiddle.net/TBJ83/3/

EDIT

For better performance and alternative ways to handle things, you can try the following:

$(function () {

    // Define static variables once
    var $myIFRAME   = $(".iframe-class"),
        ogWidth     = 700,
        ogHeight    = 600,
        ogRatio     = ogWidth / ogHeight,
        windowWidth = 0,
        resizeTimer = null;

    function setIFrameSize() {
        if (windowWidth < 480) {

            var parentDivWidth = $myIFRAME.parent().width(),
                newHeight      = (parentDivWidth / ogRatio);

            $myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
        } else {
            $myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
        }
    }

    $(window).resize(function () {

        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            windowWidth = $(window).width();
            setIFrameSize();

        }, 75);

    }).trigger("click");
});

Answer №2

You can achieve this effect by using only CSS like so:

iframe {
  height: 300px;
  width: 300px;
  resize: both;
  overflow: auto;
}

Adjust the height and width to your desired minimum size as it appears to only expand, not shrink.

Answer №3

Check out this shortened code for setting iframe size: http://jsfiddle.net/TBJ83/2/

<div class="container">
    <iframe id="myframe" src="http://www.cnn.com/"></iframe>
</div>

<script>
$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var parentDivWidth = $("#myframe").parent().width();
    var parentDivHeight = $("#myframe").parent().height();
    $("#myframe")[0].setAttribute("width", parentDivWidth);
    $("#myframe")[0].setAttribute("height", parentDivHeight);
}
</script>

I prioritized readability in my approach, but you could further optimize it for brevity and speed...

function setIFrameSize() {
    f = $("#myframe");
    f[0].setAttribute("width", f.parent().width());
    f[0].setAttribute("height", f.parent().height());
}

By using one selector, you minimize DOM traversal and improve efficiency.

Answer №4

If you are a Prestashop user, here is how I implemented the code.

Incorporated the following code in the cms.tpl file:

{if $cms->id==2}
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="text/javascript" src='../themes/myheme/js/formj.js'></script>
<div style="width: 100%; height: 800px;">
<iframe style=" width: 100%; height: 100%; border: overflow: auto;" src="https://cnn.com"></iframe>
</div>
{/if}

Next, created a new js file named formj.js and inserted the code below:

$(function () {

    //initialize these variables once as they remain static
    var $myIFRAME   = $(".iframe-class"),
        ogWidth     = 970,
        ogHeight    = 800,
        ogRatio     = ogWidth / ogHeight,
        windowWidth = 0,
        resizeTimer = null;

    function setIFrameSize() {
        if (windowWidth < 480) {
            var parentDivWidth = $myIFRAME.parent().width(),
                newHeight      = (parentDivWidth / ogRatio);
            
            $myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
        } else {
            $myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
        }
    }

    $(window).resize(function () {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            windowWidth = $(window).width();
            setIFrameSize();
        }, 75);

    }).trigger("click");
});

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

What is the process for incorporating linear-gradient coloring into the background of a Material UI Chip component?

Is it possible to incorporate a linear-gradient below color as a background for Material UI Chip? linear-gradient(to right bottom, #430089, #82ffa1) The version of Material UI I am working with is v0.18.7. <Chip backgroundColor={indigo400} style={{widt ...

Error message thrown in MERN application due to "not a function" issue in mongoDB database collection

Attempting to establish a connection with MongoDB while following an outdated tutorial from 2014. The tutorial is based on a different version of everything, causing inconsistencies in features. I am currently facing a problem where my MongoDB refuses to c ...

Determine whether the request was made using ajax or traditional non-ajax methods

While testing the PHP code below, I noticed that the headers in the request do not indicate that it is JavaScript sending the request instead of a non-JavaScript user: Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 AlexaToolba ...

Axios encounters difficulty retrieving the response data following a POST request

When using axios to post data and fetch a response, I am encountering an issue where the data is successfully posted but the response data cannot be printed. This works correctly in Postman, so I'm not sure if the problem lies with the backend or fron ...

Using Angular: Linking an href tag with a JSON key

I am working with a JSON object that includes the following value: {test_link : www.test.com} My goal is to retrieve this value and use it as a link in an HTML <a> tag, like so: <a href={{test_link}}> test </a> However, I am encounter ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

Using RequireJS with ASP.NET MVC for Efficient Script Bundling

There are a couple of things I am puzzled about. I have been delving into learning RequireJS and employing it in tandem with ASP.NET MVC bundling & minification. I have set up a separate configuration file for RequireJS which contains the bundling details ...

Issues with transitioning Jquery mobile menu integration from mobile to desktop resolution

Having difficulties incorporating a jquery menu for mobile with the provided code (see below). The issue arises when activating the mobile menu and then resizing the browser window to desktop size, where the menu's class selector has a display:none at ...

Email link spilling out from within image hyperlink

My website, located at , is experiencing an issue where the small envelope icon's mailto link is overflowing to the whole box instead of just the image itself. If anyone could provide assistance in resolving this issue, it would be greatly appreciate ...

Can a JavaScript class have a property that returns an array?

To those more experienced in node red development, this may be obvious, but I'll ask anyway. Within my node red flow, I have a function node containing a javascript class that only exposes static members. Here's an example: class MeasurementsLis ...

The process in mocha does not execute when using await

"It" in the Mocha testing framework does not execute when using the await keyword. My approach involves employing functions for asynchronous file reading and then processing the test based on the returned value. I utilize these file read functions multipl ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Crosschecking form password with MySQL database for verification

As a newcomer to PHP, I am facing challenges while setting up a login system. My struggle lies in verifying if the password entered in a form matches the corresponding email stored in a MySQL database (considering the email address was also submitted on th ...

Modify the values of all cells within a specific column in a table by utilizing a 2D array for both rows and cells

https://codesandbox.io/s/1p770371j The demonstration above showcases a table where data can be modified in each cell, and the 2D array keeps track of which row and column the data changes occur. A new button has been added to the column header titles. Th ...

React router refreshes children when switching routes, without needing to reconcile

I am facing a scenario where multiple routes share the same component and I need to maintain its state, but the current behavior makes it nearly impossible. Check out this live example (observe the elapsed seconds): View the code on CodeSandbox: https:// ...

"Enhancing pagination with AJAX to seamlessly add new data instead of overwriting existing data

I am working on implementing a PHP Based Pagination feature and I want to enhance it using ajax for better page load performance. The issue I am facing is that the ajax function is appending the entire navigation page (which is navigated through paginatio ...

The touchstart event is activated when you touch an item within

Is it possible to retrieve the index of ul li elements with touchstart, similar to how it can be done with a click function? <ul id = "list" ontouchstart="touchStart(event,'issues')"> <li> ...

DirectUpload is failing to trigger directUploadWillStoreFileWithXHR for file storage

I have implemented Rails ActiveStorage on an ECS class import { DirectUpload } from "@rails/activestorage"; function createDirectUpload(file, source, controller) { return new DirectUpload(file, source.url, source.token, source.attachmentName, ...

Display tabular information using a Bootstrap modal popup

I am facing formatting challenges while working with bootstrap. My goal is to display data in tabular form within a modal-body. Is this feasible? From what I have observed, modals can only be implemented using div tags. http://getbootstrap.com/javascrip ...

Can I send a DELETE request with request body and headers using Axios?

When working with Axios in ReactJS, I am attempting to send a DELETE request to my server. In order to do this, I need to include the following headers: headers: { 'Authorization': ... } The body of the request consists of: var payload = { ...