Using jQuery to Create Responsive iframe (YouTube Video Embed example)

I wrote this post because I was created a news feed with images and video. With bootstrap, the images are very simple to make responsive to a container by adding the class "img-responsive." However, the youTube videos were not as straight-forward because they were embedded into the container in an iframe.

The HTML

  • Create an div container to hold your responsive video.
  • <div class='video-container'></div>
  • Place the iframe inside the div container and give it an id. Do not include a width and height on the iframe.
  • <iframe id='responsive-video' src='https://www.youtube.com/embed/7ecYoSvGO60' frameborder='0' allowfullscreen></iframe>
That's it for the HTML. Next, we need to add some CSS.

The CSS

  • In the CSS, set the width of your container box and apply any additional style such as background color, padding, etc.
  • .video-container {width:80%; margin:auto; padding:2em; border-radius:5px; background-color:#EBEBEB;}
The rest is in the JavaScript. This example uses jQuery so make sure you include jQuery in your page. You can do that by copying and pasting the following code to the head section of your HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

The jQuery

  • Make sure that your code is placed within the jQuery document ready function. This example uses the shorthand notation.
  • $(function() {
    });
  • Create a function to calculate the resize proportionally by the container size.
  • function resize_video(){
       //Get the width of the container
       var container_width = $('.video-container').width();
    
       //set the new width to the container_width 
       var new_width = container_width;
    
       //calculate the new height proportionally
       //for this you will need to know the original height and width and can use the following formula: 
       //new height = original height * new width / original width 
       //In this example we use standard youTube video proportion (560 * 315)
       var new_height = (315 * new_width) / 560;
    
       //set the width and height of the iframe by id
       $('#responsive-video').width(new_width);
       $('#responsive-video').height(new_height);
    }
    
  • Call this function initially when the page loads (at the top of the document ready function).
  • Call this function when the browser is resized.
  • $( window ).resize(function() {
        resize_video();
      });

Working Example

Try resizing your browser window to see the video resize.

Comments