Jugando con jQuery para auto-embeber videos de YouTube

June 15th, 2011 | Categories: Foto / Video, Proyectos, Tecnología | Tags: , , , ,

Usando jQuery podemos convertir automáticamente los links de un foro que apuntan a YouTube en videos embebidos. Les comparto el resultado de lo que tuve que hacer para un foro.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/ui-lightness/jquery-ui.css" type="text/css" />
<script type="text/javascript"> 

function embedYouTubeVideo(strId) {
    var result = '<div class="embedded_video">\n';
    result += '<object width="640" height="390">\n';
    result += '<param name="movie" value="http://www.youtube.com/v/'+strId+'&hl=en_US&feature=player_embedded&version=3"></param>\n';
    result += '<param name="allowFullScreen" value="true"></param>\n';
    result += '<param name="allowScriptAccess" value="always"></param>\n';
    result += '<embed src="http://www.youtube.com/v/'+strId+'&hl=en_US&feature=player_embedded&version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></embed>\n';
    result += '</object>\n';
    result += '</div>\n';
    return result;
}

$(function() {
    $('a[class=bbc_link]').each(function(){
        url = $(this).attr('href');
        matches = url.match(/^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=([\w\-_]+))(?:\S+)?$/i);
        if( matches ) { $(this).replaceWith(embedYouTubeVideo(matches[1])); }
        matches = url.match(/^http:\/\/youtu.be\/([\w\-_]+)$/i);
        if( matches ) { $(this).replaceWith(embedYouTubeVideo(matches[1])); }
    });
});
</script>