Consider the code snippet below:
<div class="viewport">
<iframe src="youtube.com/blabla"></iframe>
</div>
Accompanied by this CSS:
.viewport {
height: 100vh;
width: 100%;
}
iframe {
position: absolute;
}
If we take into account that the video playing within the iframe has an aspect ratio of 16:9, can a script be written to stretch the iframe beyond its parent's size so that it overflows and hides the black bars present?
To illustrate, let's look at two scenarios that the script should address:
https://i.sstatic.net/3CsGH.png https://i.sstatic.net/iRiuJ.png
In the first scenario, where black bars are visible on the left and right sides of the video, the script would need to stretch the iframe both wider and taller until the black bars disappear. Similarly, in the second scenario with black bars appearing on the top and bottom, the iframe must be stretched accordingly.
While attempting to solve this issue by adjusting the width and height dynamically based on the viewport dimensions, there are cases where the black bars reappear as the aspect ratio changes. The provided script attempts to handle these situations but may not cover all scenarios effectively.
var block = $('.viewport');
var block_h = block.outerHeight();
var block_w = block.outerWidth();
var ratio = block_w / block_h;
// If viewport is landscape (black bars on left/right)
if( ratio >= 1.77777778 ) {
var video_w = (block_h * 16) / 9; // Get width of video within iframe
var total_black_bar_w = block_w - video_w; // Black bar total width
var new_iframe_w = (block_w + total_black_bar_w); // New width of the iframe needed to stretch the video wide enough to hide the black bars
var adjustment_percentage = new_iframe_w / block_w; // If we adjusted the width by 10% for example, then we also need to apply that percentage to the height
var new_iframe_h = (block_h * adjustment_percentage) + 30;
var pull_left = total_black_bar_w / 2; // how far to pull left to center the iframe outside of the parent container
var pull_top = (new_iframe_h - block_h) / 2; // same for top
}
// Portrait viewport (black bars on top/bottom)
else {
var video_h = (block_w * 9) / 16;
var total_black_bar_h = block_h - video_h;
var new_iframe_h = (block_h + total_black_bar_h);
var adjustment_percentage = new_iframe_h / block_h;
var new_iframe_w = (block_w * adjustment_percentage) + 30;
var pull_left = total_black_bar_w / 2;
var pull_top = (new_iframe_h - block_h) / 2;
}
block.find('iframe').css({
'width': new_iframe_w,
'height': new_iframe_h,
'left': '-' + pull_left + 'px',
'top': '-' + pull_top + 'px'
});