Reputation: 5281
I'd like the width of my IFrame to be one of two sizes, depending on the width of the browser window. Unfortunately the code below doesn't give the expected results, even on refresh. What am I doing wrong?
The HTML is as follows:
<p>A frame example:<br>
<iframe src="www.google.com">
</iframe>
</p>
At the beginning, I import a stylesheet that works in all regards except the following:
iframe
{
<script>
if (window.innerWidth<800px)
{
width="200";
}
else
{
width="400";
}
</script>
height="400";
}
Any ideas on what I can improve?
Upvotes: 0
Views: 224
Reputation: 927
Using css media queries is preferable but if you'd like to change the width using JavaScript, you can listen to the onresize
window event and change the width inside the event handler.
Note that I added an id
to the iframe so you can quickly select it in the JavaScript.
HTML
<iframe id="myIframe" src="www.google.com"></iframe>
JavaScript
(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;
}
}
}());
Check out the jsfiddle example
Upvotes: 1
Reputation: 2072
You can't use javascript inside css. Just use media queries to solve the problem
@media all and (max-width:800px) {
iframe {
width: 200px;
}
}
@media all and (min-width: 801px) {
iframe {
width: 400px;
}
}
Upvotes: 3