HTML5 Video Scale to Fill Container with jQuery

Posted by on December 5, 2011 in Web Design Blog | 9 comments

I’m working on a new large-background WordPress theme that I am going to release for free within the next two weeks. As part of the theme, I wanted to use a high-definition HTML5 video as the background of the landing page of the theme.

Here’s where I ran into trouble: browsers like to keep the aspect ratio of the video element within the <video> tag the same, no matter what the scale of the containing box is. I didn’t want to change the aspect ratio, I just wanted the video to fill the background and crop any overlap outside of the browser window.

There are a couple libraries that one can use to solve this problem, but I couldn’t get any of them to work for me. Here’s how I did it.

Using an HTML5 Video as a Background For a Website

I found this StackOverflow post (http://stackoverflow NULL.com/questions/4380105/html5-video-scale-modes) that was extremely helpful in figuring out how to scale video to the size of the screen. I had to edit his code a bit to get it to work for me.

 

Make sure to include jQuery in the <head> of your document:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>

 

Here is the HTML I used to get this to work:

        <video width=”1280″ height=”720″ autoplay loop id=”fullscreen_video”>
<source src=”wp-content/themes/StekPortfolio/sample_media/wildlife.mp4″ type=”video/mp4″ />
<source src=”wp-content/themes/StekPortfolio/sample_media/wildlife.ogg” type=”video/ogg” />
Your browser does not support the video tag. <!– Author’s note: this should be replaced with an image, or use the css background tag to fill the background if the browser doesn’t support HTML5 <video>–>
</video>

<script src=”wp-content/themes/StekPortfolio/script.js”></script>

Contents of script.js:

   var sxsw = {

full_bleed: function(boxWidth, boxHeight, imgWidth, imgHeight) {

// Calculate new height and width…
var initW = imgWidth;
var initH = imgHeight;
var ratio = initH / initW;

imgWidth = boxWidth;
imgHeight = boxWidth * ratio;

// If the video is not the right height, then make it so…

if(imgHeight < boxHeight){
imgHeight = boxHeight;
imgWidth = imgHeight / ratio;
}

//  Return new size for video
return {
width: imgWidth,
height: imgHeight
};

},

init: function() {
var browserHeight = Math.round(jQuery(window).height());
var browserWidth = Math.round(jQuery(window).width());
var videoHeight = $(‘#fullscreen_video’).height();
var videoWidth = $(‘#fullscreen_video’).width();

var new_size = sxsw.full_bleed(browserWidth, browserHeight, videoWidth, videoHeight);

$(‘#fullscreen_video’)
.width(new_size.width)
.height(new_size.height);
}

};

jQuery(document).ready(function($) {

/*
* Full bleed background
*/

sxsw.init();

$(window).resize(function() {

var browserHeight = Math.round($(window).height());
var browserWidth = Math.round($(window).width());
var videoHeight = $(‘#fullscreen_video’).height();
var videoWidth = $(‘#fullscreen_video’).width();

var new_size = sxsw.full_bleed(browserWidth, browserHeight, videoWidth, videoHeight);

$(‘#fullscreen_video’)
.width(new_size.width)
.height(new_size.height);
});
})

The calculation for the full_bleed function was not changed from Drew Baker @ StackOverflow’s original code. All credit goes to him for that solution.

The main problem I ran into using this solution was that jQuery was not reading the size of the original video correctly – it was telling me the size of the video was 150 by 300 pixels when I was sure that the video was 720p. Because it was reading the size values incorrectly, it was calculating the proportion to scale to incorrectly and letterboxing the video. Ensure that your id tag in the HTML matches up with the tag identifier in the jQuery script. Also make sure you specify the size of the video when declaring the <video> tag in the HTML.

 

Here is the CSS I used to tie everything together and make the video display as a background.

#fullscreen_video
{
background: #FF0000;
position: fixed;
top: 0px;
left: 0px;
z-index: -1000;
}

This code could be easily modified to scale a video to fill a div tag or any container for that matter. You’d have to edit the jQuery so that it measures the size of the video’s container rather than the viewport of the browser. This is the code you’d need to modify:

var browserHeight = Math.round(jQuery(window).height());
var browserWidth = Math.round(jQuery(window).width());

It took me about four hours to get everything working the way I wanted it to. Hopefully this guide will help to expedite this process for some.

Don’t hesitate to Contact Me (http://www NULL.epicwebsites NULL.com/contact-me) if you have any questions about how I got this to work or suggestions on how to improve this code.

 

 

ADDENDUM:

The above code can be used for scaling other elements too. If you want to have a dynamic large image background that scales to fit the screen -well- the code above can be reworked to make any tag work. I changed my code so that it would fill everything of the “fill” class. You can email me if you’re interested in the code.

9 Comments

  1. I Love you man! 3 hours trying to find a way to do this and with your code, first try : Success!
    Thanks a lot and thank of stackoverflow guy too!

    • Glad my post was of use!

  2. Awesome blog post! Had me up all night trying to figure out how to get my background to scale properly. Now the next thing, get the video to delay until the preload finishes. Please let me know if you can point me in the right direction. Thanks again for the post!

    • Glad that I could help! For getting the video to delay until the preload finishes, that’s also a JS thing. Found this post: http://stackoverflow.com/questions/5138077/html5-video-file-loading-complete-event (http://stackoverflow NULL.com/questions/5138077/html5-video-file-loading-complete-event)

      How did we survive before stackoverflow?

  3. I am trying to get a video to play filling the screen completely, play the video (11 seconds in length) and fade out during the last 2 seconds. I used your exact code and that works brilliantly–thank you for that. The next step is I wrapped it in a div, set {display: none}; and wrote some jQuery to get it to show when a button is clicked. That also works amazingly well. The problem is that when the div (‘#video’) shows, it pushes everything else out of the way until it fades out. The very last thing one sees is the layout snapping back into place when (‘#video’) completes fading out. I’ve messed around with {z-index} to no avail, and examined jQuery lightbox codes (they use z-index!) and can’t figure out how to get this to work without moving the rest of the elements on the page when it is called. Any suggestions?

    here’s what I wrote to get the video to show when a button is clicked:

    $(document).ready(function(){
    var v= document.getElementById(“my_video_1″);
    $(‘#show’).click(function(){
    $(‘#video’).show();
    $(‘#video’).delay(9000).fadeOut(2000);
    if (v.paused) {
    v.play();
    } else {
    v.pause();
    }
    });
    });

    • John-
      Check your CSS for #video. In order to stop elements from displacing other eelements, make sure that the div is set to position: fixed; or position:absolute;. The default setting is position: relative and this will cause elements to displace other elements. If that doesn’t work, let me know, and we can talk about the other possibilities.

      Thanks for reading!
      Alex

  4. So I’m a student, which I’m going to use as an excuse as to why I missed {display:block} for the video. So…any workarounds for that? I’ll do some new searches as well and i’ll let you know if I find a solution. Thanks!

  5. Got it to work! Thanks!

  6. Did you ever launch the free theme?

Trackbacks/Pingbacks

  1. HTML5 Video Scale to Fill Container with jQuery | Epic Websites | Best Web Design Maryland | HTML5 POWA ? | Scoop.it (http://www NULL.scoop NULL.it/t/html5-powa/p/775746695/html5-video-scale-to-fill-container-with-jquery-epic-websites-best-web-design-maryland) - [...] HTML5 Video Scale to Fill Container with jQuery | Epic Websites | Best Web Design Maryland ...

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>