Jugando con jQuery para auto-embeber videos de YouTube y Vimeo

October 1st, 2011 | Categories: Foto / Video, Proyectos, Tecnología | Tags: , , , ,

A modo de actualización del post anterior sobre cómo embeber videos de YouTube directamente parseando los links de una página, sumamos ahora la posibilidad de auto-embeber videos de Vimeo.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<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 embedVimeo(strId) {
    var result = '<iframe src="http://player.vimeo.com/video/'+strId+'?portrait=0" width="640" height="390" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>\n';
    return result;
}

$(function() {
    $('a[class=bbc_link]').each(function(){
        url = $(this).attr('href');
        // YouTube
        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])); }
        // Vimeo
        matches = url.match(/^http:\/\/vimeo.com\/([\d]+)(?:\S+)?$/i);
        if( matches ) { $(this).replaceWith(embedVimeo(matches[1])); }
    });
});
</script>
No comments yet.