Word Count: 342

The issue

The conventional method to embed a video on a website that YouTube offers is through the use of embed code in this format. The URL being used is differ from the direct URL on the youtube page.

<iframe width="560" height="315" src="https://www.youtube.com/embed/xxxxxxxxxxx" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

The solution

In order to facilitate the Shopify users to use the direct URL, a section can be created to allow the user to input the URL so that the section can format the URL to the required format.

Create a section with the following code. The CSS in %stylesheet% makes the iframe responsive to change of screen size that always maintain the same aspect ratio.

<div class="container">

    {% assign videoId = section.settings.video_url | split: '?v=' %}

    <iframe class="responsive-iframe" src="https://www.youtube.com/embed/{{ videoId[1] }}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>
    </iframe>
</div>
 
{% schema %}
  {
    "name": "Video",
    "settings": [
         {
              "type": "text",
              "id": "video_url",
              "label": "YouTube video URL"
         }
     ]
  }
{% endschema %}

{% stylesheet %}
   .container {
      position: relative;
      overflow: hidden;
      width: 100%;
      padding-top: 56.25%; /* 16:9 Aspect Ratio (divide 9 by 16 = 0.5625) */
   }

   /* Then style the iframe to fit in the container div with full height 
   and width */
   .responsive-iframe {
     position: absolute;
     top: 0;
     left: 0;
     bottom: 0;
     right: 0;
     width: 100%;
     height: 100%;
   }
{% endstylesheet %}

Note: the “position: absolute” forces the video to sit within the padding-top area which has an aspect ratio 16:9.

Reference