Automatically insert Youtube video into a div

Asked

Viewed 2,838 times

1

On the site I’m developing, there’s an element div, 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 on that div.

Has anyone ever done this? There are some plugin?

  • Yes, you can check this link https://developers.google.com/youtube/2.0/developers_guide_protocol_video_feeds#User_uploaded_videos

  • It seems to be what I need, but I saw the message: "Note: The Youtube Data API (v2) was officially suspended on March 4, 2014. See our suspension policy for more information"

1 answer

1


I solved it that 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 downloads a video feed from a channel (in this case, the Back Door). Then, a loop is made that takes the URL of each video, and applies a "fix" that turns it into the embed URL of Youtube. Finally, the embed HTML code is mounted, which is added to the div "videos".

The reason for the 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 to use 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!

  • guy I really wanted to do this with Soundcloud using theEmbed, I found some examples but I only found append the body a div with the iframe inside and not an append of a specific html like your example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.