jQuery: turn YouTube links into video players
by zachreynolds
HTML
<p><a class="youtube-link" href="http://www.youtube.com/watch?v=a_fD19yR3Ww">Video Title</a></p>
<div class="feed_entry"><div class="mm"><h3><a href="https://www.youtube.com/watch?v=JR17dnlLd40" target="_blank">Cuttlefish Look Like Squid—and Like Crabs, and Like Algae, and Like Rocks | National Geographic</a></h3><div class="content"> </div></div> <div class="mm"><h3><a href="https://www.youtube.com/watch?v=1PDjVDIrFec" target="_blank">What is Acid Rain? | National Geographic</a></h3><div class="content"> </div></div> <div class="mm"><h3><a href="https://www.youtube.com/watch?v=NwZzmTuhs3M" target="_blank">Will Snowshoe Hares Win a Race Between Evolution and Climate Change? | National Geographic</a></h3><div class="content"> </div></div> <div class="mm"><h3><a href="https://www.youtube.com/watch?v=jEhdNWKDtk4" target="_blank">Creepy Yet Heartwarming: Centipede Mother "Hugs" Its Babies | National Geographic</a></h3><div class="content"> </div></div> <div class="mm"><h3><a href="https://www.youtube.com/watch?v=HKRL6Y7Oyvw" target="_blank">High-Speed Video Shows How Flattie Spiders Attack With World's Fastest Spin | National Geographic</a></h3><div class="content"> </div></div> </div>
CSS
.youtube-box,
.youtube-frame {
display:block;
width:420px; /* video width */
height:315px; /* video height */
background-color:black;
background-size:100%;
position:relative;
border:none;
margin:0px auto 15px;
}
.youtube-box span {
display:block;
position:absolute;
top:0px;
right:0px;
bottom:0px;
left:0px;
}
.youtube-box .youtube-title {
background-color:rgba(0,0,0,0.4);
font:bold 15px Verdana,Arial,Sans-Serif;
color:white;
text-shadow:0px 1px 2px black;
bottom:auto;
line-height:30px;
height:30px;
overflow:hidden;
padding:0px 15px;
}
.youtube-box .youtube-bar {
background: #000;
height:35px;
top:auto;
}
.youtube-box .youtube-bar .yt-bar-left {
background: #999;
}
.youtube-box .youtube-bar .yt-bar-right {
background: #999;
}
.youtube-box .youtube-play {
cursor:pointer;
width:83px;
height:56px;
top:50%;
left:50%;
margin:-28px 0px 0px -42px;
background: #999;
color: #fff;
line-height: 56px;
text-align: center;
text-transform: uppercase;
}
.youtube-box .youtube-play:hover {
background-color: #000;
}
JavaScript
$(function() {
$('h3 a').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_title = $(this).text();
$(this).replaceWith('<div class="youtube-box" style="background-image:url(http://img.youtube.com/vi/' + yt_id + '/0.jpg);"><span class="youtube-title">' + yt_title + '</span><span class="youtube-bar"><span class="yt-bar-left"></span><span class="yt-bar-right"></span></span><span class="youtube-play">Play</span></div>');
$('div.youtube-box').click(function() {
$(this).replaceWith('<iframe class="youtube-frame" src="http://www.youtube.com/embed/' + yt_id + '"></iframe>');
});
});
});