JQuery set iframe height depending on iframe source - javascript

I am using the follow script to set the height of the YouTube iframe so it keeps a nice 16:9 aspect ratio. The width is always 100% of the container.
The script should only set the height for YouTube videos. This works if the source of all the iframes on the page is the same. The Youtube embeds are correctly set, soundcloud embeds are ignored, however, once I use a Youtube and a Soundcloud source, it sets both. This makes sense as the iframe is not targeted to only set the height of those that include youtu in the source.
How do I make it set only the height of iframes where the source includes youtu ?
<script>
function iframeSizing() {
$('iframe[src*="youtu"]').each(function() {
var containerWidth = $('iframe').width();
iframeWidth = containerWidth;
iframeHeight = 0.5625 * iframeWidth;
$('iframe').css({
'height': iframeHeight + 'px'
});
});
};
$(window).resize(iframeSizing);
$(document).ready(iframeSizing);
</script>
thanks

Your issue is that you are using the $('iframe') selector over and over again, meanwhile your function doesn't actually know which iframe you are referring to.
Your selector inside the .each() function should be $(this) instead of $(iframe).
So, $(this).width() and $(this).css()
Basically, the way the .each() function works is it loops through all elements with $('iframe[src*="youtu"]') and then inside of that function, to refer to the current element that the loop is on you should use the selector $(this)

Related

page has different height when inside an iframe

I've googled a bit and there were a few leads, but I couldn't get any of those leads to work:
I have a page that has an iframe with the src pointing to an external page (cross domain). When the child/iframed page loads, it posts a message of its height. I put a console.log of the height in the javascript. If I open that page in a separate window (type the iframe's src URL in a separate tab, in other words), the console logs the expected height.
However, when I open the parent page with the iframe, the console logs either 0 or a very incorrect value of 150. I've looked through the css and html, and I don't have any specifications of 150.. Anyone have a clue what's going on here?
Abstracted code:
Parent HTML:
...
<iframe src="example.childpage.com" scrolling="no" frameBorder="0"></iframe>
...
Parent Javascript:
...
$(document).ready(function(){
window.addEventListener('message', function(m){
var messageData = m.data;
if(messageData.type=='document-loaded' &&
messageData.hasOwnProperty('height'){
resize_iframe(messageData.height); //function defined else where
//and works
};
});
...
IFrame Javascript:
...
$(document).ready(function(){
var body = document.body;
var html = document.documentElement;
var maxHeight = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
//Logs height correctly when opened in a separate window but not when
//iframed
console.log("POSTING HEIGHT", maxHeight);
window.parent.postMessage({'type':'document-loaded', 'height': maxHeight},
PARENT_HOST_URL); //PARENT_HOST_URL defined elsewhere
});
...
I realize I have a mixture of jquery and vanilla javascript here; I've done both $(document).height() and the Math.max() shown above to get the height, but both ways still have the same issue.
Much thanks!
ok I finally found a good solution:
$('iframe').load(function() {
this.style.height =
this.contentWindow.document.body.offsetHeight + 'px';
});
Because some browsers (older Safari and Opera) report onload completed before CSS renders you need to set a micro Timeout and blank out and reassign the iframe's src.
$('iframe').load(function() {
setTimeout(iResize, 50);
// Safari and Opera need a kick-start.
var iSource = document.getElementById('your-iframe-id').src;
document.getElementById('your-iframe-id').src = '';
document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
document.getElementById('your-iframe-id').style.height =
document.getElementById('your-iframe-
id').contentWindow.document.body.offsetHeight + 'px';
}
I had a function that looped through not-yet-accessible elements and called $(element).hide() on them -- which sets the style display: none.
Turns out calculating the height of an element is respective of its visibility on the actual page, regardless of it being in an iframe. So the browser couldn't see it, so the height was being miscalculated (still weird it was returning a random 150px value). That explains why it was calculating correctly on a separate page.
Instead of doing hide(), I just set the visibility to hidden and that fixed my issue of getting the incorrect heights.

jquery 1.8 and higher, set the height of a div to the same as another div

As of Jquery 1.8 a change was made when getting the height() of an element. I have a CSS div height set to auto with the image inside dictating the height and width of the div by using % and auto), and when the window loads i use Jquery to get the height of the element and make another div next to it the same height. After researching this I have noticed that it is returning the height before the CSS has set the new height that is set by the image. 1.7 allowed this, but 1.8 and up does not. Is ther a work around.
this is the css
#element1{ width:80%; height:auto;}
#element1 img{width:100%; height:auto};//this allows the image to resize with the page responsively.
jQuery...
$(window).ready(
function(){
var x = $("#element").height();
alert(x); // this would return what the height was dynamically set as by the css in 1.7, but 1.8 returns a small number that i am pretty certain is just the padding added to 0px
});
Hopefully this makes sense, and someone has a work around.
Thanks
Instead of listening on $(window).load(), which might stall proper height assignment until all resources have been successfully loaded, you can listen to successful loading on each <img> instance and trigger proper height calculation.
However since in your question you only have one element you are concerned with setting height dynamically, I have reduced my script without the need to loop through all <img> instances on the page. Assuming that you have the following markup:
<div id="element1">
<img ... />
</div>
You can create a new image, check if it is loaded and then instruct jQuery to run the height calculations and set a new height when this is done:
$(function() {
var $img = $('<img />', {
'src': $('#element1 img').attr('src')
});
$img.load(function() {
$('#element2').css('height', $('#element1').height());
});
});
There's a mismatch between your css selector (#element1) and your jquery selector ('#element'). Start by making them both match whatever you have on your html element. You could also wrap this in a timeout so your image will have time to fully load.
$( document ).ready(function() {
setTimeout(function() {
$('#element2').height( $('#element1').height() );
}, 2000});
});

Get video size in youtube

I'd like to set the viewport to the video size in a youtube video. In any flash video, the <embed> tag's flashvars attribute has a detail like adaptive_fmts=size%3D1280x720 and I need 1280 and 720 from that.
What I'm wondering is, is there a way to set the viewport (called #player-api) to this size purely in CSS3? Or baring that, what is a simple javascript I could load to handle it?
found on my own..
there is no CSS method .. none before CCS4 at least.
one way, made easier with jQuery, is:
var jqs = document.createElement('script');
jqs.src = "//code.jquery.com/jquery-1.10.2.min.js";
document.getElementsByTagName('head')[0].appendChild(jqs);
//wait until jQuery has a chance to load. then...
jQuery.noConflict();
var wh = jQuery("#player-api embed").attr("flashvars").match(/adaptive_fmts=size\%3D(.\d+)x(.\d+)/);
// now wh[1] is width and wh[2] is height
jQuery("#player-api").width(wh[1]).height(wh[2])
this uses javascript's .match on the element to return the details in an array.

set fancybox height with jquery

I want to show a fancybox on my page displaying an iframe with a source of another domain that has dynamic height (since within the iframe I'll go to different pages or might have some dynamic content). I have access to the other domain's code as well. So I can use postMessage to send the iframe's source's height to my page. But I can't seem to figure how to change the fancybox's height through code.
I tried setting the height of all the divs that contain the iframe, including the iframe itself:
document.getElementById('fancybox-frame').height = parseInt(height);
document.getElementById('fancybox-content').height = parseInt(height);
document.getElementById('fancybox-outer').height = parseInt(height);
document.getElementById('fancybox-wrap').height = parseInt(height);
and I know that I'm getting the height through all right since it works perfectly on a directly integrated iframe.
Anyone got any ideas?
Thanks
Edit:
I also tried $.fancybox.update() but I'm not really sure on how to implement that:
$.fancybox({
'height': height
});
$.fancybox.update();
Have you tried the built in $.fancybox.update() method? The the documentation suggests (under API Methods) that this method should provide the functionality you're looking for.
Found it, you have to change following attributes
document.getElementById('fancybox-content').style.height = parseInt(height) + 'px';
document.getElementById('fancybox-frame').height = parseInt(height);

iframe dynamic height resizing

Hi I currently have 2 pages (index.html and iframe_contents.html). Both are on the same domain.
I am currently trying to get the iframe to dynamically resize based on the contents size.
I was using this to assist me http://benalman.com/code/projects/jquery-resize/examples/resize/ and it works if the iframe_contents body tag gets larger or smaller on Firefox and IE 7/8/9 but for webkit it only can grow and can never shrink
I've narrowed it down to the body tag in iframe_contents.html not shrinking when content height changes but only in the iframe. When iframe_contents.html is not in a iframe if I shrink / enlarge elements the bodies overall height changes.
Is this a webkit specific issue?
After reading lots of answers here they all had the same issue with not resizing smaller when needed. I think most people are just doing a one-off resizing after the frame loads, so maybe don't care. I need to resize again anytime the window size changes. So for me, if they made the window narrow the iframe would get very tall, then when they make the window larger it should get shorter again. This wasn't happening on some browsers because the scrollHeight, clientHeight, jquery height() and any other height I could find with DOM inspectors (FireBug/Chrome Dev Tools) did not report the body or html height as being shorter after the iframe was made wider. Like the body had min-height 100% set or something.
For me the solution was to make the iframe 0 height, then check the scrollHeight, then set to that value. To avoid the scrollbar on my page jumping around, I set the height of the parent (that contains the iframe) to the iframe height to keep the total page size fixed while doing this.
I wish I had a cleaner sample, but here is the code I have:
$(element).parent().height($(element).height());
$(element).height(0);
$(element).height($(element).contents().height());
$(element).parent().height("");
element is my iframe.
The iframe has width: 100% style set and is inside a div with default styles (block).
Code is jquery, and sets the div height to the iframe height, then sets iframe to 0 height, then sets iframe to the contents height. If I remove the line that sets the iframe to 0 height, the iframe will get larger when needed, but never smaller.
This may not help you much but here is a function we have in what would be your iframe_contents.html page. It will attempt to resize the iframe in which it is loaded in a sort of self-resizing, cross-browserish, pure-JavaScript kind of way:
function makeMeFit() {
if (top.location == document.location) return; // if we're not in an iframe then don't do anything
if (!window.opera && !document.mimeType && document.all && document.getElementById) {
parent.document.getElementById('youriframeid').style.height = (this.document.body.offsetHeight + 30) + "px";
} else if (document.getElementById) {
parent.document.getElementById('youriframeid').style.height = (this.document.body.scrollHeight + 30) + "px"
}
}
You could put calls to it in a resize() event or following an event that changes the height of your page. The feature-testing in that method should separate out WebKit browsers and pick the correct height property.

Categories