jQuery iFrame fitter plugin

Plugin to make sure YouTube iFrames fit within their container element properly.

by kshep92

HTML

<div class="c-post-view__content">
  <iframe class="video-frame" src="https://www.youtube.com/embed/mJaHARCfcA0" frameborder="0" allowfullscreen></iframe>
</div>

CSS

.c-post-view__content {
  box-sizing: border-box;
  padding: 16px;
  border: 1px solid;
}

iframe {
  margin: 0 auto;
  width: 100%;
  display: block;
}

JavaScript

(function($) {

	$.fn.fitFrames = function() {
  	var $allVideos = $("iframe[src*='youtube.com']");
  	var $fluidContainer = $(this);
    
    function resize() {
      var containerWidth = $fluidContainer.width();
      var viewportWidth = $(window).width();
      $allVideos.each(function() {
          var $frame = $(this);
          var bestHeight = Math.floor((9 * $frame.width()) / 16) //16:9 aspect ratio
          $frame
          	.removeAttr('height')
            .removeAttr('width')
          	.height(bestHeight);
        });
    }
    
    $(window).on('resize', resize);
    
    resize();
    
    return this;
  }
})(jQuery);

(function($) {
	$(".c-post-view__content").fitFrames();
})(jQuery);