Skip to content

Instantly share code, notes, and snippets.

@iftee
Created January 23, 2017 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iftee/7cebca6705cc2704062737c8859b5fb0 to your computer and use it in GitHub Desktop.
Save iftee/7cebca6705cc2704062737c8859b5fb0 to your computer and use it in GitHub Desktop.
Responsive YouTube embed with max-width for WordPress
( function( $ ) {
'use strict';
// Assumptions:
// 1. The post content (and the video) will be inside a wrapper with class .post-content
// 2. The video aspect ratio is 16:9
// 3. The video will take the full width of the .post-content but will not go beyond a certain width
$( window ).on( 'load resize', function() {
// Take the width of the wrapper
var contentWidth = $( '.post-content' ).width();
// Define te maximum width of the video
var videoMaxWidth = 800; // Change this pixel value to something that works for you
// Resize all YouTube iframes according to the wrapper size with 16:9 aspect ratio
$( '.post-content iframe[src*="https://www.youtube.com"]' ).each( function() {
if ( $( this ).width() < contentWidth ) {
$( this ).width( videoMaxWidth );
$( this ).height( videoMaxWidth * 9 / 16 );
} else {
$( this ).width( contentWidth );
$( this ).height( contentWidth * 9 / 16 );
}
} );
} );
} ) ( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment