Skip to content

Instantly share code, notes, and snippets.

@sarhov
Last active February 22, 2021 17:21
Show Gist options
  • Save sarhov/4cb7ac5f6c669ac5d4dad4cd392c0f17 to your computer and use it in GitHub Desktop.
Save sarhov/4cb7ac5f6c669ac5d4dad4cd392c0f17 to your computer and use it in GitHub Desktop.
YouTube video into div wrapper to make it responsive. Plain JS solution.
.videoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
height: 0;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
const wrapVideos = () => {
const iframeVideos = document.querySelectorAll('iframe[src*="youtube.com/embed/"]');
if (iframeVideos) {
for (const [i, v] of iframeVideos.entries()){
let original = v;
let wrapper = document.createElement('div');
wrapper.classList.add(`videoWrapper`, `video--${i}`);
wrapper.appendChild(original.cloneNode(true));
original.replaceWith(wrapper);
}
}
}
wrapVideos();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment