public
Last active

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 really needed) detects click on the image, it overwrites container HTML using the iframe defined in the comments. Because of the ?autoplay=1 it will start playing when inserted. Bonus: Play button is shown above image using CSS. Bonus 2: if you need to hide controls, instead of using a regular iframe, you will have to insert the object/embed with controls=0 param.

  • Download Gist
youtube-poster-frame.css
CSS
1 2 3 4 5 6 7 8 9 10
.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; }
youtube-poster-frame.html
HTML
1 2 3 4
<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>
youtube-poster-frame.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
$(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");
});
});

This is a handy script, thankyou. I had one issue in IE8 however – nodeTypes are not constants in IE8 as explained here with workaround: http://webbugtrack.blogspot.co.uk/2007/10/bug-256-dom-nodetype-constants-are-not.html

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.