replaceYoutube

find YouTube links and replace them with embedded objects

by elclanrs

HTML

<a href="http://www.youtube.com/watch?v=47BohS9YxIo&feature=g-all-lik&context=G2394b7aFAAAAAAAAAAA"></a>
<a href="http://www.youtube.com/watch?v=DsKxhxTONa4&feature=relmfu"></a>

CSS

body { margin: 50px; }
input {
    padding: .3em;
    margin: 1em 0;
}
.youtube {
    display: inline-block;
    padding: .5em;
    border: 1px solid #999;
    border-radius: 5px;
    background: #ffffff;
    background: -moz-linear-gradient(top, #ffffff 0%, #e2e2e2100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e2e2e2));
    background: -webkit-linear-gradient(top, #ffffff 0%,#e2e2e2 100%);
    background: -o-linear-gradient(top, #ffffff 0%,#e2e2e2100%);
    background: -ms-linear-gradient(top, #ffffff 0%,#e2e2e2 100%);
    background: linear-gradient(top, #ffffff 0%,#e2e2e2 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 );
    box-shadow: 0 0 2px rgba(0,0,0,.3);
}

JavaScript

$.fn.linkToYoutube = function(ops) {
  var o = $.extend({
    width: 480,
    height: 320,
    params: ''
  }, ops)
  return this.each(function () { 
    var $link = $(this),
        href = $link.attr('href'),
        id = /\?v\=(\w+)/.exec(href)[1],
        iframe = '<iframe style="display: block;"'+
        ' class="youtube-video" type="text/html"'+
        ' width="' + o.width + '" height="' + o.height +
        ' "src="http://www.youtube.com/embed/' + id + '?' + o.params +
        '&amp;wmode=transparent" frameborder="0" />'
    $link.replaceWith(iframe) 
  })
}

$('a').linkToYoutube()