Responsive YouTube Player API with the responsive-youtube.js lib

responsive-youtube.js for use with YouTube Player API

The need to create this library was when I tried to use
YouTube Embedded Players with width="100%":

<iframe width="100%" src="<video ID>" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

But the height does not match the proportion of the width.

Then I tried to use the YouTube Player API with width: '100%':

player = new YT.Player('<element ID>', {
width: '100%',
videoId: '<video ID>'

But I was also not able to make the player work well in responsive and adaptive layouts. However, I noticed that placing the player without specifying the width and height makes the player start with the size based on the approximate proportion of the original size of the video, with this information I decided to get the width and height using Element.clientWidth and Element.clientHeight from the original player and then applied a simple calculation in the following situations:

The simple calculation:

if (originalWidth != originalHeight) 
element.height = currentWidth / (originalWidth / originalHeight);
} else
element.height = currentWidth;

Partially solved problem. However, there are systems that load specific things on “demand”, such as paging using XMLHttpRequest with History API (like Vue.js, Angular, and the like), to solve this the best option looked like the MutationObserver API with { childList: true }.

So as more than one need arose to resolve this, I decided it would be better to turn it into a library and share it.

The library has 3,15KB (minified) and 1,55KB when gzipped from webserver (like ngx_http_gzip_module or mod_deflate).


You can download from releases responsive-youtube.min.js and put in your page:

<script src="responsive-youtube.min.js"></script>

Or use CDN:

<script src=""></script>

Using npm:

npm i responsive-youtube.js

And import using:

const SimpleCopy = require('responsive-youtube.js');

Using ECMAScript modules:

import SimpleCopy from 'responsive-youtube.js'

Add player in your page

A simples example:

<!-- embed video in page -->
<div data-ry-video="Tdjk9dhT_AU"></div>
<!-- embed video in page without "responsive" -->
<div data-ry-video="5ABos9UTfJU" data-ry-ignore="true"></div>
<script src="responsive-youtube.js"></script>


php, javascript, mysql, python, html5, css3, html, css, jquery /