Automatically insert Youtube video into a div

1

In the site I'm developing, it has a div element, where it needs to automatically capture YouTube videos from a channel, that is, if the user / channel uploads a video, it will automatically show the last video in this div .

Has anyone done this yet? Are there any plugins?

    
asked by anonymous 17.06.2014 / 14:15

1 answer

1

I solved it this way:

HTML:

<div class="videos"></div>

Javascript (with jQuery):

$(function() {
    // Baixar URLs do feed do canal
    $.get('http://gdata.youtube.com/feeds/api/users/portadosfundos/uploads?max-results=10&alt=json', function(result) {

        var entries = result.feed.entry;

        for(var i=0; i<entries.length; i++) {
            var url = entries[i].link[0].href;   

            // Transformar URL de vídeo em URL de embed
            // ANTES: http://www.youtube.com/watch?v=aDqExWjK49Y&algumacoisaaqui
            // DEPOIS: http://www.youtube.com/embed/aDqExWjK49Y
            url = url.replace('/watch?v=', '/embed/');
            url = url.substring(0, url.indexOf('&'));

            // Fazer append dos vídeos
            $('.videos').append('<iframe width="480" height="270" src="' + url + '" frameborder="0" allowfullscreen></iframe>');
        }
    });
});

Explanation:

Basically get a video feed of a channel down (in this case, the Port of Funds). Then a loop is taken that takes the URL of each video, and applies a "fix" that turns it into the Youtube embed URL. Finally, embed the HTML code of the embed, which is added to the "videos" div.

The reason for URL "fix" is that YouTube did not provide a variable with only the video ID in the feed. It would have been very convenient in this case. =)

Example in jsFiddle

Note: In normal situations I would have tried using the Youtube oEmbed system , which provides a more reliable HTML code, but I ended up not being able to use it right because it is a cross-domain request, etc. In any case, it might be useful for you, take a look!

    
17.06.2014 / 15:12