Setting the Scale of an iFrame - javascript

I'm creating a website which hosts games, and like many, I use the wonderful <iframe> tag to get the game from a seperate directory. I am trying to get the <iframe> to size itself to 600px wide and let the height automatically adjust itself.
I have tried using the CSS transform property, but it has to be a percent, not an amount in pixels. I have also tried using Javascript to get the scroll height and the scroll width of the <iframe> and set the width to 600px while setting the height to the height of the content.
Here's my markup, script, and stylesheet.
HTML:
<div class="game-border" id="gameBack">
<iframe src="http://superfungames.com/tetris/" class="game-frame" id="gameCont" frameborder="0" scrolling="no"></iframe>
</div>
<!-- Counteract the evil effects of centering the game-border and game-frame by using position absolute !-->
<div class="breaker" id="breaker"></div>
Javascript:
var gameBack = document.getElementById('gameBack');
var breaker = document.getElementById('breaker');
var iFrame = document.getElementById('gameCont');
var iframeWin = iFrame.contentWindow || iFrame.contentDocument.parentWindow;
var iFrameHeight = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
iFrame.style.height = iFrameHeight + 'px';
gameBack.style.height = gameBack.scrollHeight + 25 + 'px';
gameBack.style.width = gameBack.scrollWidth + 25 + 'px';
//Counteract position absolute. Additional number is like margin-top.
breaker.style.height = gameBack.scrollHeight + 10 + 'px';
CSS:
.game-frame {
width: 600px;
height: auto;
overflow: visible;
}
.game-border {
background-color: #63d68f;
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
display: flex;
justify-content: center;
align-items: center;
overflow: visible;
}
I expect that the <iframe> would be 600px wide and the height of the content tall, however, it is 600px and only has the very top of the content showing.

The iframe tag counts with a width attribute, you only need to add width="{number_of_pixels}". Example: <iframe src="{any_website_url}" widht="600"></iframe>, this sets the width to 600px.
It should work in most sites (I guess), however this doesn't work with the website you are using. It seems that it uses some script that redirects you to their websit instead of displaying it in an iframe.
To solve this you can add the attribute sandbox. This will block some features of the website, like the one that redirects you to their website. Example: <iframe src="{any_website_url}" sandbox></iframe>. I am not sure if this will break anything about the game itself. You can try to investigate more.
Your HTML will be something like this. There is no need to change the js file nor the css file.
<div class="game-border" id="gameBack">
<iframe src="http://superfungames.com/tetris/" width='600' class="game-frame" id="gameCont" frameborder="0" scrolling="no" sandbox></iframe>
</div>
<!-- Counteract the evil effects of centering the game-border and game-frame by using position absolute !-->
<div class="breaker" id="breaker"></div>
More info:
HTML iframe width attribute
Why does <iframe src=“https://”></iframe> redirect the page in IE 11?

Related

Dynamic and 100% iframe

I have a website with a header and a footer. Let's call it domain.com.
Now on a second domain I have 2 files:
page1.php with a height of 1500px page2.php with a height of
800px
Now do I want to add both pages on my domain.com (not at the same time, but with for example domain.com/1 and domain.com/2) with an iframe that shows the full page content (important: of page1.php and page2.php) and adds it between the header and footer.
The iFrame should be without a scrollbar and should look for a user like there is no iFrame.
How can I make a dynamic iFrame that shows the full page (page1.php or page2.php) but also automaticly sets the sizes depending on the page content (as page1.php is larger than page2.php)?
// EDIT:
I forgot to enter important things. The site I want to add as iFrame is a shop website and so is dynamic. There is no fixed height of the site. So I can't use px in height because that would a) show too less (the rest would be "cut out") or show too much (the rest would be simply white). I hope you understant what I mean.
Using <iframe> to display content is a bit dated, but if it's what you want to do, take a look at the following demo:
Demo
Basically, you just need to make sure your scrolling and frameborder attributes are properly turned off:
<iframe src="https://xhynk.com/" scrolling="no" frameborder="none"></iframe>
and it helps to set your CSS to something like this:
iframe {
display: block;
width: 100vw;
height: 400px;
}
display: block removes any inline margin (usually 4px) from the iframe)
width: 100vw will set it to your viewport width (though use 100% instead if you have a sidebar or parent container that's not as wide as the viewport
and set your height to whatever pixel size the content is.
So your domain.com/1 page will look something like this:
<header>Page 1</header>
<iframe src="page1.php" scrolling="no" frameborder="none" style="display: block; width: 100vw; height: 1500px;"></iframe>
<footer>© Jelly</footer>
And domain.com/2 will look something like:
<header>Page 2</header>
<iframe src="page2.php" scrolling="no" frameborder="none" style="display: block; width: 100vw; height: 800px;"></iframe>
<footer>© Jelly</footer>
You may care to read up on the:<iframe> Element Documentation for more information.
For dynamic heights you can only do this if your don't have Cross Domain issues to worry about, but you can modify the height of the window after it's loaded:
Add the onload attribute to your iframe:
<iframe id="iframe1" src="page2.php" scrolling="no" frameborder="none" onload="iframeResize()"></iframe>
JavaScript
function iframeResize() {
var iframe = document.getElementById('iframe1');
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
}

CSS/HTML Dynamically Resizing Iframe through Javascript

In my HTML code, I'm setting my Iframe width value to 95% of the width. I want the height to dynamically resize according to the set aspect ratio. I have made a javascript script to try the dynamically resizing but when i run my HTML it doesn't resize the height.
Here is my html for the iframe:
<div class="video">
<tr>
<td>
<iframe src="https://embed.theguardian.com/embed/video/news/video/2016/dec/27/cassetteboy-remix-the-news-2016-review-special-video" scrolling="no" onload="resizeiframe(this);" allowfullscreen></iframe>
</td>
</tr>
</div>
Here is my css:
.video {
}
.video iframe {
align: center;
width: 95%;
margin-top: 180px;
float: top;
position: relative;
}
and here is my javascript:
<script>
//this is javascript
//it is used to dynamically resize the height of the iframes based on screen width
function resizeiframe(object) {
//assign the aspect ratio to a variable
private float aspectratio = (6/19);
//set the objects height to the object's width multiplied by the aspect ratio
object.style.height = (object.style.width * aspectratio);
}
</script>
Can anyone help?
Two Solutions
First, you had a few issues with your original JS:
You were not getting the width of the iframe correctly (use element.offsetWidth or the like)
You need to assign the unit when setting a width (px, etc.)
You were typing aspectratio incorrectly as private float instead of var or private aspectratio: number; (Typescript) -- unless you are using another superset JS language and it wasn't tagged in the question.
JavaScript: (Modification to your original)
function resizeiframe(object) {
//assign the aspect ratio to a variable
var aspectratio = (6/19);
//set the objects height to the object's width multiplied by the aspect ratio
object.style.height = (object.offsetWidth * aspectratio) + "px";
}
// This is just quick and dirty to grab the element -- do something better
resizeiframe(document.getElementsByTagName("iframe")[0]);
Working Plnkr
Doing this via JavaScript may also require that you call resizeiframe on window.resize to compensate for user's resizing of the browser window.
OR
This can also be accomplished with a CSS-Only solution (no JavaScript needed), if you're not against using vw (viewport width units) instead of px (pixels).
CSS:
iframe {
width: 95vw;
height: calc(95vw*(6/19));
}
HTML
<iframe src="https://embed.theguardian.com/embed/video/news/video/2016/dec/27/cassetteboy-remix-the-news-2016-review-special-video" scrolling="no" onload="resizeiframe(this);" allowfullscreen></iframe>
Working Plnkr
With this solution, browser resizing is handled automagically.
Note: In both solutions, I removed .video wrapper element to simplify the answer, but this can be easily added back.
You should add px.
object.style.height = (object.style.width * aspectratio) + "px";

Image within an Image using HTML, CSS and JavaScript

I created a regular image in HTML. Then, dynamically via JavaScript, I added an image within the initial image. However, I am having an issue where if a user were to zoom in or out, the internal image does not stay in the same place. And it is possible that a user could zoom in my case, anytime, and I really need the internal image not to move. I do not have anything fancy, and I am trying all sorts of ways to get this to work, so if you have a way that uses HTML and CSS, I could add it to my code, because I have tried many different avenues and changed my HTML around multiple times. However, if you would like my code, in depth, I would be glad to supply it with you. Any help is greatly appreciated, or if you simply need more clarification, I can do that as well, thanks in advance.
Here is an example of the code that adds an image to an image, and has the issue that I explained above:
$(document).ready(function() {
$('#myImgId').click(function(e) {
var offX = event.clientX;
var offY = event.clientY;
margin = 20;
if (offX > margin) offX -= margin;
if (offY > margin) offY -= margin;
var signHereImage = document.createElement("img");
signHereImage.setAttribute('src', 'imageInserted.jpg');
signHereImage.setAttribute('class', 'overlays');
signHereImage.style.left = offX + "px";
signHereImage.style.top = offY + "px";
document.body.appendChild(signHereImage);
});
});
<form id="form1" runat="server">
<div>
<img src="page3.jpg" alt="PDF Image" id="myImgId" />
</div>
</form>
This is for the most part what it is, I know that I am doing something incorrectly, I just do not know what for certain, thanks again in advance.
I would use the background-image property to achieve this. You can place the image in a div, give that div a background image, and then position the image relative to the div. Here's a working example:
div {
position: relative;
height: 500px;
background-image: url(https://images.unsplash.com/photo-1413781892741-08a142b23dfe?dpr=2&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=&bg=);
background-size: cover;
}
img {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 200px;
}
<div>
<img alt="img" src="https://images.unsplash.com/photo-1483086431886-3590a88317fe?dpr=2&auto=format&fit=crop&w=1500&h=2247&q=80&cs=tinysrgb&crop=&bg=" />
</div>
Consider what changes when a user zooms in or out on a web page. The viewport size changes, relative to the content on the page.
You are probably styling the internal image based on something related to the viewport. The automatic width of block elements is calculated from the width of the viewport if other constraints are not available. For example, an element with the following CSS properties moves around with the right edge of the viewport:
position: absolute;
right: 20px;
See a demo.
Other elements, perhaps including the external image of yours, are by default laid out line-by-line, starting from the top left. This discrepancy can cause some elements of the page to move with respect to others when zooming or resizing the window.
Review how you instruct the browser to lay out these two images, and make sure that, if they depend on the size of the viewport, they depend on it in the same way.

Re size iframe based on width of window

I have an iframe embedded in a third party website, which I cannot edit in any way.
I want the iframe to re-size according to the width of the window.
If I was able to edit the whole page, this would not be a problem.
However, when setting the size of an element in %, it uses the parent of that element to size from. In the case of the page I am working with, the parent elements do not re-size, so this does not work.
What I need, is a way of telling the iframe to re size, based solely on the width of the window, and preferably using only CSS.
Is this possible using only CSS? If not is it possible using JQuery or JavaScript?
Try this:
http://jsfiddle.net/6aLxaag8/2/
This jsfiddle loads a second jsfiddle in the iframe.
There's a hardcoded style attribute on the IFrame that sets the width; 100vw or 100% of the width of the viewing window in which the element sits, regardless of it's position in the DOM. As you don't have access to the parent page you'll need to use a style attribute and you may not be able to use javascript to add it (check cross site scripting).
Support isn't perfect with vw units, but it's close.
PS, it's hard to know if this will work without trying it in your context, please let me know :-)
I have encountered that problem before and I use this css trick, this adjust to the width & height of any wrapper/div so if you have embed an iframe inside a div with 'height: 620px' and 'width: 420px' the iframe size adjust to the div's height and width. Just change both width & height of the div to 100% percent.
.content_here {
width: 420px;
height: 620px;
}
iframe#iframecontent {
display:block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
<div class="content_here">
<iframe id="iframecontent" src="http://www.bootstrapcdn.com/" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto"></iframe>
</div>

Scrolling an iframe with JavaScript?

I dynamically load an iframe with JavaScript. After it's loaded, how can I make it scroll down a specific number of pixels (ie. after the page in the iframe has loaded, how can I make the iframe scroll by itself to the a specified region of the page?)
You can use the onload event to detect when the iframe has finished loading, and there you can use the scrollTo function on the contentWindow of the iframe, to scroll to a defined position of pixels, from left and top (x, y):
var myIframe = document.getElementById('iframe');
myIframe.onload = function () {
myIframe.contentWindow.scrollTo(xcoord,ycoord);
}
You can check a working example here.
Note: This will work if both pages reside on the same domain.
Inspired by Nelson's and Chris' comments, I've found a way to workaround the same origin policy with a div and an iframe:
HTML:
<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>
CSS:
#div_iframe {
border-style: inset;
border-color: grey;
overflow: scroll;
height: 500px;
width: 90%
}
#frame {
width: 100%;
height: 1000%; /* 10x the div height to embrace the whole page */
}
Now suppose I want to skip the first 438 (vertical) pixels of the iframe page, by scrolling to that position.
JS solution:
document.getElementById('div_iframe').scrollTop = 438
JQuery solution:
$('#div_iframe').scrollTop(438)
CSS solution:
#frame { margin-top: -438px }
(Each solution alone is enough, and the effect of the CSS one is a little different since you can't scroll up to see the top of the iframed page.)
Inspired by Nelson's comment I made this.
Workaround for javascript Same-origin policy with regards to using.ScrollTo( ) on document originating on an external domain.
Very simple workaround for this involves creating a dummy HTML page that hosts the external website within it, then calling .ScrollTo(x,y) on that page once it's loaded. Then the only thing you need to do is have a frame or an iframe bring up this website.
There are a lot of other ways to do it, this is by far the most simplified way to do it.
*note the height must be large to accommodate the scroll bars maximum value.
--home.html
<html>
<head>
<title>Home</title>
</head>
<frameset rows="*,170">
<frame src=body.htm noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
<frame src="weather.htm" noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
</frameset>
</html>
--weather.html
<html>
<head>
<title>Weather</title>
</head>
<body onLoad="window.scrollTo(0,170)">
<iframe id="iframe" src="http://forecast.weather.gov/MapClick.php?CityName=Las+Vegas&state=NV&site=VEF&textField1=36.175&textField2=-115.136&e=0" height=1000 width=100% frameborder=0 marginheight=0 marginwidth=0 scrolling=no>
</iframe>
</body>
</html>
Use the scrollTop property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):
<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
A jQuery solution:
$("#frame1").ready( function() {
$("#frame1").contents().scrollTop( $("#frame1").contents().scrollTop() + 10 );
});
Based on Chris's comment
CSS
.amazon-rating {
width: 55px;
height: 12px;
overflow: hidden;
}
.rating-stars {
left: -18px;
top: -102px;
position: relative;
}
HAML
.amazon-rating
%iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}
Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.
#frame {
margin-top:200px;
}
The main issue when programming the scroll is related to getting the whole document embedded into the page, remember than an Iframe would be a full-page (head and all) inside your main doc, for this reason, before actually scrolling, you need to get the inner document, not just the container, so you can actually scrollTo.
We add a validation to sendure compatibility, and the differences betwen contentDocument and windows can be found here
Havign this, the final code would be:
var $iframe = document.getElementByID('myIfreme');
var childDocument = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
childDocument.documentElement.scrollTop = 0;
I've also had trouble using any type of javascript "scrollTo" function in an iframe on an iPad. Finally found an "old" solution to the problem, just hash to an anchor.
In my situation after an ajax return my error messages were set to display at the top of the iframe but if the user had scrolled down in what is an admittedly long form the submission goes out and the error appears "above the fold". Additionally, assuming the user did scroll way down the top level page was scrolled away from 0,0 and was also hidden.
I added
<a name="ptop"></a>
to the top of my iframe document and
<a name="atop"></a>
to the top of my top level page
then
$(document).ready(function(){
$("form").bind("ajax:complete",
function() {
location.hash = "#";
top.location.hash = "#";
setTimeout('location.hash="#ptop"',150);
setTimeout('top.location.hash="#atop"',350);
}
)
});
in the iframe.
You have to hash the iframe before the top page or only the iframe will scroll and the top will remain hidden but while it's a tiny bit "jumpy" due to the timeout intervals it works. I imagine tags throughout would allow various "scrollTo" points.

Categories

Resources