Automatic adaptation of the iframe on the site


24-07-2018
Денис Л.
Оптимизация сайта
Automatic adaptation of the iframe on the site

When we post a video from YouTube on our page, we are faced with the fact that YouTube always sets us fixed video sizes, specifying them in the width and height attributes. And if we want the video to be adaptive? So that it is always the full width of the parent container on all types of devices? Then we have to either write a bunch of styles, or put up with the fact that on large screens the video takes up a smaller part of the container, and on mobile devices does not...

I wrote a script, you can use it on my site.

So, the automatic adaptation of iframes on the pages of the site

First, for each iframe, we assign a class iframeAdaptive.

Example:

<iframe class="iframeAdaptive" width="560" height="315" src="https://www.youtube.com/embed/4LYl3PgDKx8?rel=0" frameborder="0"></iframe>

Important: the available width and height in the attributes must be left, the script will calculate proportions for them.


Next, insert the script on our page:

<script>
document.addEventListener("DOMContentLoaded", function() { // use the page load event, not including pictures and stuff
    let iframes = document.querySelectorAll('.iframeAdaptive');
    iframes.forEach(function(i) { // We sort through the available Iframe with the class assigned to us
        let iframeWidth = i.width; // take the width from the 'width' attribute
        let iframeHeight = i.height; // we take the height from the 'height' attribute
        let iframeParent = i.parentNode; // determine the parent element of our Iframe
        let parentWidth = parseInt(getComputedStyle(iframeParent)['width'])-parseInt(getComputedStyle(iframeParent)['padding-left'])-parseInt(getComputedStyle(iframeParent)['padding-right']); // Take the parent container and calculate the width we need, without taking into account 'padding', 'margin' и 'border'
        let iframeProportion = parentWidth / iframeWidth;
        i.setAttribute('width', parentWidth); // set the width to our Iframe
        i.setAttribute('height', iframeHeight * iframeProportion); // establish the height of our Iframe
    });
});
</script>

No additional libraries (jQuery, etc.) are required to run the script.