Better Way to Resize Video using jQuery
by Bandicoot Marketing on | Posted in Articles | 5 comments
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(),
5 comments for “Better Way to Resize Video using jQuery”