Skip to content

Instantly share code, notes, and snippets.

@zigotica
Last active July 8, 2023 10:12
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save zigotica/4438876 to your computer and use it in GitHub Desktop.
Save zigotica/4438876 to your computer and use it in GitHub Desktop.
Very simple method to add custom poster frame to youtube video without using youtube API. This code is also valid in browsers not supporting window.postMessage (API uses postMessage). The trick is adding the iframe in a comment. Javascript reads comment contents and saves iframe definition to a var. When JQuery (for the sake of brevity, not real…
.video { position: relative; padding-bottom: 56.25%; /* 16:9 */ height: 0; }
.video img { position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; z-index: 20; cursor: pointer; }
.video:after { content: ""; position: absolute; display: block;
background: url(play-button.png) no-repeat 0 0;
top: 45%; left: 45%; width: 46px; height: 36px; z-index: 30; cursor: pointer; }
.video iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
/* image poster clicked, player class added using js */
.video.player img { display: none; }
.video.player:after { display: none; }
<div class="video">
<img src="poster.jpg">
<!-- <iframe width="940" height="529" src="http://www.youtube.com/embed/rRoy6I4gKWU?autoplay=1" frameborder="0" allowfullscreen></iframe>-->
</div>
$(function() {
var videos = $(".video");
videos.on("click", function(){
var elm = $(this),
conts = elm.contents(),
le = conts.length,
ifr = null;
for(var i = 0; i<le; i++){
if(conts[i].nodeType == 8) ifr = conts[i].textContent;
}
elm.addClass("player").html(ifr);
elm.off("click");
});
});
@nikisebi
Copy link

Works perfectly, and makes pages with a bunch of videos load fast. Thanks!

@flower-spring
Copy link

I tried this technic for add a poster to a youtube video. It didn't worked at beginning, but I suspect it was linked to youtube url. I had the impression jsfiddle couldn't read this url : <!-- <iframe width="940" height="529" src="http://www.youtube.com/embed/rRoy6I4gKWU?autoplay=1" frameborder="0" allowfullscreen></iframe>-->
but with link get from share button on a youtube video, it worked. (july 2023)
For example, this worked :
<!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/0AugFrZPP9U" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> -->
jsfiddle link - poster for youtube video - with new youtube link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment