Skip to content

Instantly share code, notes, and snippets.

@yannickoo
Last active August 29, 2015 14:03
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 yannickoo/5c4cbb031fdf2ef2cef7 to your computer and use it in GitHub Desktop.
Save yannickoo/5c4cbb031fdf2ef2cef7 to your computer and use it in GitHub Desktop.
Scale videos so that they are fit into a container
$('video.fit').each(function() {
var $this = $(this);
var $container = $this.parent();
var containerWidth = $container.width();
var containerHeight = $container.height();
$this[0].addEventListener('loadedmetadata', function() {
var videoWidth = $this[0].videoWidth;
var videoHeight = $this[0].videoHeight;
var scaleH = containerWidth / videoWidth;
var scaleV = containerHeight / videoHeight;
var scale = scaleH > scaleV ? scaleH : scaleV;
videoWidth = scale * videoWidth;
videoHeight = scale * videoHeight;
$this.width(videoWidth);
$this.height(videoHeight);
$this.css('margin-left', videoWidth / 2 * -1);
$this.css('margin-top', videoHeight / 2 * -1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment