Better Way to Resize Video using jQuery
by c.bavota | Posted in Articles | 5 comments
Aug
29
2012
I have already written a little jQuery snippet to resize videos but I came across an article by Chris Coyier with an approach that I thought worked a lot better. Though I did add a few tweaks to it:
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
// Responsive videos
var all_videos = $( 'iframe[src^="http://player.vimeo.com"], iframe[src^="http://www.youtube.com"], object, embed' );
all_videos.each(function() {
var el = $(this);
el
.attr( 'data-aspectRatio', el.height() / el.width() )
.attr( 'data-oldWidth', el.attr( 'width' ) );
} );
$(window)
.resize( function() {
all_videos.each( function() {
var el = $(this),
newWidth = el.parents( 'p' ).width(),
oldWidth = el.attr( 'data-oldWidth' );
if ( oldWidth > newWidth ) {
el
.removeAttr( 'height' )
.removeAttr( 'width' )
.width( newWidth )
.height( newWidth * el.attr( 'data-aspectRatio' ) );
}
} );
} )
.resize();
})(jQuery);
/* ]]> */
</script>
Now your videos will only be resized if they are larger than the parent container. In the instance above, I have set the parent container to the paragraph tag surrounding the video (in WordPress, a paragraph tag is automatically added to each paragraph). If your site uses a different container, you can easily change that one line to the tag, ID or class of your parent container.
newWidth = el.parents( '.class-name' ).width(),



Thanks for the snippet!
Im using you Theme. Check out please: http://www.jurnalizd.ru/
The if + re-size function is very helpful, especially for us non-coders. Thanks!
Hello Bavota,
Great article! But I notice that this code only works well when you load the screen to full width (or width greater than the width of the video) and then resize. However, if you load it on an iPhone then it doesn’t seem to come out quite right because Youtube and Vimeo force the height and width to be set in-line to iframe. As a result the height of the video on a mobile device is too big. Are you getting a similar issue?
I’m just looking for a quick fix. If I manage to sort it I’ll let you know.
Thanks again for the great article.
Afzaal
Hi, I found that the following change helped to make this code function properly on all devices. I made the following change:
Original
.attr( ‘data-aspectRatio’, el.height() / el.width() )
Revised
.attr( ‘data-aspectRatio’, el.attr( ‘height’ ) / el.attr( ‘width’ ) )
Hope this helps other people that found the same issue as myself.
Thanks for the info. I’m going to do some testing with both and try to figure out why it works with one and not the other.