Adjusting the width of an IFrame using CSS and JavaScript

I'm trying to adjust the width of my IFrame based on the size of the browser window. However, my current code is not producing the desired outcome even after refreshing the page. Can anyone pinpoint where I am going wrong?

Here is the HTML snippet:

<p>A simple frame example:<br>
    <iframe src="www.google.com">
    </iframe>
</p>

Initially, I include a stylesheet that functions correctly except for this particular aspect:

iframe
{
<script>
    if (window.innerWidth<800px)
    {
    width="200";
    }
    else
    {
    width="400";
    }
</script>
height="400";
}

Any suggestions on how I can enhance this setup?

Answer №1

Using JavaScript within CSS is not possible. Instead, you can utilize media queries to address the issue.

@media all and (max-width:800px) {
    iframe {
        width: 200px;
    }
}

@media all and (min-width: 801px) {
    iframe {
        width: 400px;
    }
}

Answer №2

It is recommended to use css media queries for changing the width of an element. However, if you prefer to do so using JavaScript, you can listen to the onresize window event and adjust the width inside the event handler.

Don't forget that I included an id for the iframe for easy selection in your JavaScript code.

Here's how you would structure it in HTML:

<iframe id="myIframe" src="www.google.com"></iframe>

And here's the corresponding JavaScript code:

(function() {
    var iframe = document.getElementById('myIframe');
    iframe.height = 400;

    window.onresize = resizeIframe;

    function resizeIframe() {
        if (window.innerWidth < 800) {
            iframe.width = 200;
        }
        else {
            iframe.width = 400;
        }
    }
}());

You can also view a live example of this implementation on jsfiddle.

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

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

What are some ways to utilize CSS variables for enhancing component styles within Svelte?

Presented here is a straightforward component called Text.svelte. It utilizes a CSS variable to prevent unnecessary duplication: <div> <span class="t1">t1</span> <span class="t2">t2</span> </div> ...

How can the parent div adjust its height to match the tallest child div?

Currently working on a web project where I have a div named "page", housing two other divs - one on the left called "navigation" and the one on the right named "content". I am aiming to set the height of the "page" div to match the height of the tallest di ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

I've encountered an issue when attempting to use innerHTML for DOM manipulation

I've been attempting to remove a specific list item <li> from the inner HTML by assigning them proper IDs. However, I'm encountering difficulties in deleting it. How can I delete these list items after clicking on the cross button? Feel fr ...

I am attempting to obtain the sum using the return function, but I am having trouble getting it to work. Would you be able to assist me in identifying what mistake I am

Can someone explain the benefits of using a return function? var a, b; function addNumbers(a, b) { a = prompt("Enter a number"); b = prompt("Enter another number"); return (a + b); } addNumbers(); ...

"What is the best way to retrieve the name of the object passed in a function in

After searching high and low, I still can't seem to find the answer to my simple question. Maybe it doesn't exist, but I won't give up just yet. So here's the scenario: I created a global prototype in Vue, essentially a global class, ...

Using Jquery to dynamically load an aspx page into a specific div element

Yesterday, I posted a question about loading an aspx page in a div tag. I have been using the code below to try and accomplish this, but so far I have been unsuccessful. Can anyone provide assistance on how to successfully load the aspx page into the div ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

Retrieve the user's unique identification number upon creation and proceed to update the database accordingly

I'm trying to create a cloud function that automatically adds 50 points to the "points" field in the database whenever a new user is created using the "onCreate((user)" function. The goal is to simply detect when a new user is created, retrieve their ...

There are three dropdown menus in my form, and the options available in each one are based on the choices made in the

I need to create a form with three dropdown menus. Each menu should display options based on the selection made in the previous one. For example, there should be dropdowns for categories, car brands, and car models. The car brand dropdown should only sh ...

Refusing to handle HTTP requests in Node and Express API for MongoDB interactions

I am currently in the process of creating a basic API for performing CRUD operations on a local mongo database. Despite having what seems like correct code, the CRUD operations result in pending requests that never seem to complete. Below are snippets of ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

How can I show the remaining paragraph text upon clicking a button in a responsive manner using CSS and JavaScript?

I want to add a nice animation effect to the height of my text when a button is clicked. I've managed to achieve this by setting a height: 30px with overflow: hidden initially, and then toggling a class with height: 300px. However, I'm facing an ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

Inject some vibrancy by incorporating color in the space between the navbar and banner on the

Hello! I am relatively new to front-end development and I am currently working on converting a PSD design to code for a project. I am struggling a bit to understand certain concepts but I am eager to learn and improve. I am using Bootstrap 4 for this proje ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

Move the search bar to the left side of the screen instead of the

Is there a way for the search bar in my navbar's dropup menu to transition from right to left? Currently, the dropup menu is positioned on the far right of the screen as desired, but when I click on the search button, the search bar extends off the sc ...

Utilizing Django templates to display a dictionary containing nested tuples

Here's my dictionary: { '123': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'met ...