User Manipulated Frame - HTML/CSS/JS - javascript

How can I make the below frame, once loaded, to allow for the user to drag and scale the size? Is this possible with HTML/CSS/JS?
<script>
var frame;
function addFrame() {
frame = document.createElement('iframe');
frame.height = "200px";
frame.width = "200px";
frame.setAttribute('id', 'superFrame');
document.body.appendChild(frame);
}
function loadGoogle() {
frame.setAttribute('src','http://www.google.com')
}
</script>
Left is what I have, right is what I want but with the user setting the size via dragging the frame.
Image

src Responsive IFrames — The Right Way!
remove width and height attributes
set up a parent div for the iframe
make the containing div responsive, and the iframe with the following size/positioning rules:
iframe {
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}

Related

Resizable video does not fully fit to parent div

I have a video element which is draggable and resizable.
I would like the video element to fit 100% to the parent div
when I resize it, but this is where I fail to do so.
This is what I have so far:
CSS
.my-div
{
width: 320px;
height: 240px;
top: 200px;
left: 400px;
position:absolute;
z-index: 9;
background-color: #28a745;
}
JS
let video_div = document.createElement('div');
video_div.id = 'video-div'
$(video_div).addClass('my-div')
$("body").append(($(video_div).draggable().resizable()))
let video_element;
video_element = document.createElement('video');
$(video_element).attr('id', 'my_video');
$(video_element).attr('class', 'video-js vjs-default-skin');
$(video_element).attr('width', '100%');
$(video_element).attr('height', '100%');
$(video_element).attr('controls', ' ');
$(video_element).attr('preload', 'auto');
$(video_element).attr('data-setup', '{}');
let source = document.createElement('source');
$(source).attr('type', "video/mp4");
$(source).attr('src', "http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4");
$(video_div).append(video_element)
$(video_element).append(source);
As you can see from this fiddle, if you try to resize
the video,it doesn't fit to the parent div
(green background appears behind)
How could I modify my code to achieve that?
EDIT: Updated Fiddle that shows the problen once I add the video-js library
By default, the video tag tries to keep the video aspect ratio.
If you want to fill your parent, you must use the CSS property "object-fit"
In your code, try to add
video_element.style.objectFit = "fill";
or, using JQuery:
$(video_element).css("object-fit", "fill");
Of course, doing this will not guarantee a perfect aspect ratio for the video.
More info about the object-fit property here https://developer.mozilla.org/it/docs/Web/CSS/object-fit
Add % to the height of the surrounding div the one called .my-div (whit this video it is 56.25%). If you change the width the height is always 56.25% of the height and the video should fit.
You can calculate the ratio on this webpage: https://www.calculatorsoup.com/calculators/math/ratios.php

the size of an iframe don't fit the real content

Good afternoon
Is simple, i need the white box height and width fit with the iframe text, how i can do it?
function resizeIframe (iframeContentWidth, iframeContentHeight) {
var container = window.frameElement.parentElement;
if (container != parent.document.body) {
container.style.width = iframeContentWidth + 'px';
container.style.height = iframeContentHeight + 'px';
}
window.frameElement.style.width = iframeContentWidth + 'px';
window.frameElement.style.height = iframeContentHeight + 'px';
return;
}
html {
background-color: #fff
}
div {
background-color: #000;
display: inline-block;
}
<div>
<iframe src="http://190.216.202.35/rxp/mobilpxr.php?stopid=502102" height="85px" width="250px" scrolling="no" frameborder="0">
</div>
At first, it's good to know, how the elements you've used in your HTML work.
Every browser has its own default size for iframes, which is used, if the size is not given by attributes or CSS. Usually the size is nearby 300x200. The body of a document loaded into iframe adapts the width of the iframe it was loaded into, and the height is defined according to the content, if any sizing for the body haven't been defined.
A div element is a block level element, which by default takes a width of 100% of its parent element, and the height depends on the content height. However, this can be changed by setting a CSS property display: inline-block for a div, when the width will be set according to the content of a div.
There's no simple way at client side to detect the size of an arbitrary content to be loaded, before it has been parsed, hence we have to wait that happen. We can wait the iframe to finish loading and parsing on a parent page (= the page containing the iframe), or we can do that in the iframe itself. The latter simplifies referencing, so we'll use it in the following example, i.e. all the following code must be included in the file which is loaded to the iframe.
The body of the iframe:
<div>
<span class="title">Capri A2</span>
<br />
<span class="big">Rutas aquí: | P17 | E31 | T31 | E21</span>
</div>
Iframe resize in the iframe:
window.onload = function () {
var bodyWrapper = document.querySelector('div'),
size;
// Adapt the size of bodyWrapper to its content. If needed, an absolute size can be set too.
bodyWrapper.style.display = 'inline-block';
// Get the size information of bodyWrapper
size = bodyWrapper.getBoundingClientRect();
// Set the iframe size
frameElement.style.width = size.width + 'px';
frameElement.style.height = size.height + 'px';
// Done!
return;
}
Try this, hope it will resolve your issue.
Set iframe "height:auto"

How can i make my script center img in div

I have concocted a little script here out of bits and pieces I have found and scraped together, but I need a little help to add an extra function to it,
First of all - this is what it is doing for me at the moment:
It resizes and crops/letterboxes an image to completely fill a div
which is a % height and a % width – it keeps doing this whenever and
whatever window resize
It keeps working seamlessly as the window is resized
The image is filling 100% the area the div covers - left to right
and top to bottom.
The image is not being squashed or stretched - just being cropped
or is overflowing.
The image is kept as small as possible, so whatever the resize -
you can still see either the very sides OR the very top and bottom of
the image.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and Safari
over XP and 7
All of these things are very important to me, please don't tell me that all i need is:
<img style="width : 100%;">
This is so much more than that. It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Now, what I want to add:
All it is, I’d like the letter box to centre on the image.
When the div is a very tall portrait or a very flat landscape I’m just getting the top or just the left hand side of the image.
I’d like the centre of the original image to stay in the centre of the resized div.
I’ve tried a few things but have drawn a blank. I’m sure the script could feed a minus top: or left: into the style but it seems if I get too many div’s in div’s IE doesn’t like it, or what am I doing wrong?
Thing is I don’t really know how to wright this stuff, I only steal bit and bobs and splat them together…
And finally the demo
And the script:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
Thanks Very Much For This.
I'm not quiet sure if that's what you're looking for, but let's try this:
*upd: the wysiwyg is not working on comments at this moment, so sorry for messy code snippets.
1.Position the div#imgarea relatively. You can then float it to the right, to replicate your right:0px declaration. Don't forget to hide the overflow, to ensure that 'letter-boxed' parts of the image stay hidden.
#imgarea {
position: relative;
width: 70%;
height: 75%;
float: right;
overflow: hidden;
top: 25%;
};
Some user agents will add paddings and margins to the body element, thus preventing the image container to slide all the way to the right. Reset those, to get rid of the gaps between the container and the edge of the browser window.
body {
margin: 0;
padding: 0;
}
As for the image itself, position it absolutely.
img {
position: absolute;
}
And finally javascript. To center the image, you need to calculate what this width/height=auto sums up to, and then reset left/top attributes respectively. Your if function needs to be adjusted just a bit; leave your variables as is:
if (height_ratio > width_ratio) {
var newWidth, newHeight, newTop;
newWidth = area_width;
newHeight = image_height/width_ratio;
newTop = -(newHeight-area_height)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = newTop;
document.images[0].style.left = 0;
}else{
var newWidth, newHeight, newLeft;
newHeight = area_height;
newWidth = image_width/height_ratio;
newLeft = -(width-area_width)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = 0;
document.images[0].style.left = newLeft;
}
I hope that if this doesn't solve the issue completely, it at least sends you in the right direction. Good luck.
I'm not sure if this will work exactly, but may get your started. I had a client request a radial gradient be fixed to the left and right of a website's main ontent section. The page was set up with dynamic widths and I had a heck of a time getting one solid image to work, so I came up with a quick css solution.
#bgHold #gradLeft{
width:248px;
height:975px;
position:fixed;
right:50%;
margin-right:399px;
background:url("../images/gradLeft.png") top center no-repeat;
}
margin-right is half of the content block's width. So basically, the gradient is fixed on the page at 50% from the right, then shoved left 50% of the content box making it line up with the edge of the content. The same idea applies to the other side.
Now, with your situation, perhaps you can set right:50%; and margin-right:imgWidth/2?

make iframe height dynamic based on content inside- JQUERY/Javascript

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe's height. The iframe should not have scroll bars.
I have a wrapper div tag inside the iframe which basically is all the content. I wrote some jQuery to make the resize happen :
$("#TB_window", window.parent.document).height($("body").height() + 50);
where
TB_window is the div in which the Iframe is contained.
body - the body tag of the aspx in the iframe.
This script is attached to the iframe content. I am getting the TB_window element from the parent page. While this works fine on Chrome, but the TB_window collapses in Firefox. I am really confused/lost on why that happens.
You can retrieve the height of the IFRAME's content by using:
contentWindow.document.body.scrollHeight
After the IFRAME is loaded, you can then change the height by doing the following:
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
Then, on the IFRAME tag, you hook up the handler like this:
<iframe id="idIframe" onload="iframeLoaded()" ...
I had a situation a while ago where I additionally needed to call iframeLoaded from the IFRAME itself after a form-submission occurred within. You can accomplish that by doing the following within the IFRAME's content scripts:
parent.iframeLoaded();
A slightly improved answer to Aristos...
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
}
</script>
Then declare in your iframe as follows:
<iframe onload="resizeIframe(this)" ...
There are two minor improvements:
You don't need to get the element via document.getElementById - as you already have it in the onload callback.
There's no need to set the iframe.height = "" if you're going to reassign it in the very next statement. Doing so actually incurs an overhead as you're dealing with a DOM element.
Edit:
If the content in the frame is always changing then call:
parent.resizeIframe(this.frameElement);
from within the iframe after the update. Works for same origin.
Or to auto detect:
// on resize
this.container = this.frameElement.contentWindow.document.body;
this.watch = () => {
cancelAnimationFrame(this.watcher);
if (this.lastScrollHeight !== container.scrollHeight) {
parent.resizeIframeToContentSize(this.frameElement);
}
this.lastScrollHeight = container.scrollHeight;
this.watcher = requestAnimationFrame(this.watch);
};
this.watcher = window.requestAnimationFrame(this.watch);
I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).
So in the parent document, add an event listener:
window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
$iframe.height(data);
break;
}
}, false);
And inside the iframe, write a function to post the message:
function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
}
Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:
<body onLoad="resize();">
Add this to the iframe, this worked for me:
onload="this.height=this.contentWindow.document.body.scrollHeight;"
And if you use jQuery try this code:
onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
you could also add a repeating requestAnimationFrame to your resizeIframe (e.g. from #BlueFish's answer) which would always be called before the browser paints the layout and you could update the height of the iframe when its content have changed their heights. e.g. input forms, lazy loaded content etc.
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
window.requestAnimationFrame(() => resizeIframe(iframe));
}
</script>
<iframe onload="resizeIframe(this)" ...
your callback should be fast enough to have no big impact on your overall performance
There are four different properties you can look at to get the height of the content in an iFrame.
document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight
Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.
function getIFrameHeight(){
function getComputedBodyStyle(prop) {
function getPixelValue(value) {
var PIXEL = /^\d+(px)?$/i;
if (PIXEL.test(value)) {
return parseInt(value,base);
}
var
style = el.style.left,
runtimeStyle = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft;
el.style.left = style;
el.runtimeStyle.left = runtimeStyle;
return value;
}
var
el = document.body,
retVal = 0;
if (document.defaultView && document.defaultView.getComputedStyle) {
retVal = document.defaultView.getComputedStyle(el, null)[prop];
} else {//IE8 & below
retVal = getPixelValue(el.currentStyle[prop]);
}
return parseInt(retVal,10);
}
return document.body.offsetHeight +
getComputedBodyStyle('marginTop') +
getComputedBodyStyle('marginBottom');
}
Other answers were not working for me so i did some changes. Hope this will help
$('#iframe').on("load", function() {
var iframe = $(window.top.document).find("#iframe");
iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
});
Just in case this helps anyone. I was pulling my hair out trying to get this to work, then I noticed that the iframe had a class entry with height:100%. When I removed this, everything worked as expected. So, please check for any css conflicts.
I am using jQuery and the code below working for me,
var iframe = $(window.top.document).find("#iframe_id_here");
iframe.height(iframe.contents().height()+'px' );
You can refer related question here - How to make width and height of iframe same as its parent div?
To set dynamic height -
We need to communicate with cross domain iFrames and parent
Then we can send scroll height/content height of iframe to parent window
And codes - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8
Rather than using javscript/jquery the easiest way I found is:
<iframe style="min-height:98vh" src="http://yourdomain.com" width="100%"></iframe>
Here 1vh = 1% of Browser window height. So the theoretical value of height to be set is 100vh but practically 98vh did the magic.
All other answers are correct but what if the iframe has some dynamic content like a map that loads later and dynamically changes your iframe scroll height. This is how I achieved it.
var iFrameID = document.getElementById('idIframe');
intval = setInterval(function(){
if(iFrameID.scrollHeight == iFrameID.contentWindow.document.body.scrollHeight){
clearInterval(intval);
}else{
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
},500)
I simply wrap the code inside setInterval which matches the iframe scroll height with iframe content scroll height then clear the interval.
in my project there is one requirement that we have make dynamic screen like Alignment of Dashboard while loading, it should display on an entire page and should get adjust dynamically, if user is maximizing or resizing the browser’s window.
For this I have created url and used iframe to open one of the dynamic report which is written in cognos BI.In jsp we have to embed BI report. I have used iframe to embed this report in jsp. following code is working in my case.
<iframe src= ${cognosUrl} onload="this.style.height=(this.contentDocument.body.scrollHeight+30) +'px';" scrolling="no" style="width: 100%; min-height: 900px; border: none; overflow: hidden; height: 30px;"></iframe>
I found the answer from Troy didn't work. This is the same code reworked for ajax:
$.ajax({
url: 'data.php',
dataType: 'json',
success: function(data)
{
// Put the data onto the page
// Resize the iframe
var iframe = $(window.top.document).find("#iframe");
iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
}
});
To add to the chunk of window that seems to cut off at the bottom, especially when you don't have scrolling I used:
function resizeIframe(iframe) {
var addHeight = 20; //or whatever size is being cut off
iframe.height = iframe.contentWindow.document.body.scrollHeight + addHeight + "px";
}
This one is useful when you require a solution with no jquery. In that case you should try adding a container and set a padding to it in percentages
HTML example code:
<div class="iframecontainer">
<iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
</div>
CSS example code:
.iframeclass{
position: absolute;
top: 0;
width: 100%;
}
.iframecontainer{
position: relative;
width: 100%;
height: auto;
padding-top: 61%;
}
The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.
In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.
.canvas-container {
position: relative;
padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
height: 0;
overflow: hidden;
}
.canvas-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
A slightly improved answer to BlueFish...
function resizeIframe(iframe) {
var padding = 50;
if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
else
iframe.height = (window.innerHeight - padding) + "px";
}
This takes in consideration the height of the windows screen(browser, phone) which is good for responsive design and iframes that have huge height.
Padding represents the padding you want above and below the iframe in the case it goes trough whole screen.
jQuery('.home_vidio_img1 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery(this).replaceWith(video);
});
jQuery('.home_vidio_img2 img').click(function(){
video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img3 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img4 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
Sample using PHP htmlspecialchars() + check if height exists and is > 0:
$my_html_markup = ''; // Insert here HTML markup with CSS, JS... '<html><head></head><body>...</body></html>'
$iframe = '<iframe onload="if(this.contentWindow.document.body.scrollHeight) {this.height = this.contentWindow.document.body.scrollHeight;}" width="100%" src="javascript: \''. htmlspecialchars($my_html_markup) . '\'"></iframe>';
Script
<script type="text/javascript" language="javascript">
$(document).ready(function(){
var height = $(window).height();
$('.myIframe').css('height', height - 200);
});
</script>
iframe
<iframe class="myIframe" width="100%"></iframe>
It's working in my case.
$(document).height() // - $('body').offset().top
and / or
$(window).height()
See Stack Overflow question How to get the height of a body element.
Try this to find the height of the body in jQuery:
if $("body").height()
It doesn't have a value if Firebug. Perhaps that's the problem.
just make iframe container position:absolute and iframe will automatically change its height according to its content
<style>
.iframe-container {
display: block;
position: absolute;
/*change position as you need*/
bottom: 0;
left: 0;
right: 0;
top: 0;
}
iframe {
margin: 0;
padding: 0;
border: 0;
width: 100%;
background-color: #fff;
}
</style>
<div class="iframe-container">
<iframe src="http://iframesourcepage"></iframe>
</div>

How do I get dynamically fluid images depending on browser window aspect ratio?

This might not be a simple question, but I try my best.
I have this example site: http://lotvonen.tumblr.com/
I have a little piece of javascript that automatically calculates the height of the inner browser window and sets that number as image wrapper div's height. Height of the image inside the wrapper is 100% of the wrapper, so that I get nice, full screen images on all normal screen sizes.
This works wonderfully on screens that are more wide than tall (desktops, laptops, etc).
But!
With screens that are more tall than wide (smartphones, iPads etc), the images get clipped from sides. I don't want that, so I have a temporary solution to have media query assigning height to auto and width to 100%, when browser screen max-width is 1024, so that no clipping occurs. But it's not a very good solution, and breaks at certain resolutions. It also destroys my JS with lower resolutions (eg. 800x600).
Here's the JS:
<script type="text/javascript">
var elems = document.getElementsByClassName('img'),
size = elems.length;
for (var i = 0; i < size; i++) {
var img = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
img.style.height=(height)+'px';
}
</script>
and here's my CSS:
.img {
max-width:100%
}
.img img {
width:auto;
}
.img img {
height:100%;
}
#media only screen and (max-width: 1024px) {
.img {
height:auto !important;
}
.img img {
height:auto !important;
max-width:100%;
}
and here's the div:
<li><div class="img"><img src="{PhotoURL-HighRes}" alt="{PhotoAlt}"/></div>
How do I get it so, that when the browser window is more tall than wide (eg. 720x1024), the images adjust by width, and when the browser window is more wide than tall (eg. 1024x720) the images adjust like they do now (by height, with the JS).
Is this possible at all? Is there a simple CSS fix to this or do I need to mess more with JS?
Thanks in advance!
You could also get the aspect in javascript on a regular basis and then add a class to the body object that would specify if it was 4:3, widescreen, or portrait. Then make it run on an interval in case the window changes size.
Example
CSS
.43 img { width: auto; }
.widescreen img { width: 100%; }
.portrait img { height: 100%; }
JavaScript
var getAspect = function(){
var h = window.innerHeight;
var w = window.innerWidth;
var aspect = w / h;
var 43 = 4 / 3;
var cssClass = "";
if (aspect > 43) {
cssClass = "widescreen";
}
else if (aspect === 43) {
cssClass = "43";
}
else {
cssClass = "portrait";
}
$("body").addClass(cssClass); // Using jQuery here, but it can be done without it
};
var checkAspect = setInterval(getAspect, 2000);
I would suggest getting the aspect ratio first in javascript. Use window.innerHeight and windows.innerWidth, and make the necessary division. Then, make this a condition. When the screen in wider than its height, set the image in css to width: 100%. Otherwise, set height: 100%.

Categories

Resources