Day 005

by Shane Robinson

It’s Friday and it’s a shortcode day!

There is a great 11ty YouTube embed plugin but it has limitations. The most important being that there is no “title” attribute on the YouTube iFrame tag.

That “title” attribute is very important for accessibility and your site will also get dinged by Lighthouse performance tests if your iFrames don’t have that “title” attribute.

So I completely removed the YouTube plugin and wrote my own YouTube shortcode that requires you provide a Title…and optionally lets you set the video start time.

Update to Code Updates

Friday afternoon I re-factored the shortcode to do the following:

  • Added default video id
  • Added default title
  • Added ability to provide start time in “m:ss” format instead of having to manually convert to seconds.
  • Added ratio so it’s user controled (default = 16:9) and doesn’t rely on a custom CSS class.

NOTE: There’s probably more “math” in my JS than needed. But I’m basically learning JS right now and this is what I could get working.

/utils/shortcodes.js

	/**
* My YouTube embed with Title, Start (optional) and Ratio (optional)
* vid = "youtubeID" : required : default = "oHg5SJYRHA0"
* vtitle = "Your title for this video" : required : default = "YouTube Video"
* vstart = "4:20" : optional
* vratio = "w:h" : optional : default = "16:9"
*/

youtube: function (vid, vtitle, vstart, vratio) {
const slug = vid ? vid : 'oHg5SJYRHA0'
const title = vtitle ? vtitle : 'YouTube Video'
const start = vstart
? vstart
.split(':')
.reduce((first, second) => Number(first) * 60 + Number(second))
: ''
const ratio = vratio ? vratio : '16:9'
const padding = ratio
.split(':')
.reduce((first, second) => (second / first) * 100)
const style = 'style="padding-bottom:' + padding + '%"'

return `<div id="${slug}" class="relative w-full" ${style}><iframe class="absolute top-0 bottom-0 left-0 right-0 w-full h-full" width="100%" height="100%" title="${title}" src="https://www.youtube.com/embed/${slug}${
start ? `?start=${start}` : ''
}
" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen loading="lazy"></iframe></div>`

},

TailwindCSS makes it easy to manage responsive elements (videos, images, etc.) but video embeds do require some work to get the correct height for the videos.

So rather than add a custom CSS class to the tailwind.css file, I buit the math into the style variable above.

Shortcode Usage

In order to use it, you just copy the YouTube video ID and use it as the first value in the shortcode. The second value is the title.

Here’s an example using my video from 2013 where I demo my design and build for a Gallery Wall System. It will start at 1:23 into the video and have a default ratio of 16:9.

{% youtube "uJ-yFkJ9ykA", "Shane Robinson's Gallery Wall System", "1:23" %}