I searched for the perfect solution to show a custom high quality thumbnail for my embed videos. I did not want to use the more complex Youtube Javascript API solution. Here is how I archived the obstacle of using a custom thumbnail or Youtube maximum resolution thumbnail and a custom play button.
The following code uses jQuery but this could be done in Vanilla Javascript.
Technical explanation to use a custom Youtube thumbnail
First, I integrate my Youtube video with a custom
div
and custom thumbnail if needed. The data attribute tags are used to provide the Youtube video id and the custom thumbnail URL.Then, on page load, for each video on a page, the Javascript code creates a placeholder with the needed thumbnail (custom or Youtube maximum resolution one). A customized play button is added on top using CSS.
Finally, a click event listener is added to the placeholder to create an embed
iframe
when clicked. When showing theiframe
the placeholder is hidden.
The explanation is short and sweet, but take a look at the code and let me know what you think !
Youtube Custom Thumbnail Image: Cédric VT (@cedric_photography) from Unsplash
Cover Image: PJ Gal-Szabo (@pjgalszabo) from Unsplash
Top comments (5)
I have a page of videos that I used this solution on, and it's working for several of them, but not all of them. Any ideas why some would work and some would not?
Thanks, this is really helpful! Have you found a way to automatically play the video once the user clicks the thumbnail? Currently it loads the iframe but it doesn't play the video. Thanks!!!!
In case someone wants to know this:
Some people attach autoplay=1, but you also need to attach mute=1 to make it autoplay. That works, but with no sound (of course). It seems like the browsers made sure we can't play the video automatically without muting them. Which makes sense for limiting the bad guys, but it also affects us the good guys :/
Hi thanks for this it works like a charm. I have a small problem where I cant play embedded video in full screen mode. Any idea how I can work around this?
Thanks again
Oh I have figured it out.
In the createIframe function, I added iframe.setAttribute("allowfullscreen", "1");
Works perfectly