Search code examples
javascriptjqueryvimeo

Dynamically get thumbnails and titles of vimeo videos


Picking up from this question: Get img thumbnails from Vimeo?

I'm trying to create a page with several vimeo videos on it.

I want to have the videos in the HTML look like this:

<div id='12345678' class='vimeo'></div>
<div id='23423423' class='vimeo'></div>

And then I want the jQuery to populate the divs with an img where the src is the thumbnail from vimeo, and an a which points to the video, and whose text is the title of the video. That is, it should end up like this:

<div id='12345678' class='vimeo'>
    <a href='https://vimeo.com/12345678'>
        <img src='url-to-thumbnail.jpg' />
        Video Title
    </a>
</div>

(Indentation added for clarity)

This is my starting point from that other question:

<script type="text/javascript">
    $.ajax({
        type:'GET',
        url: 'http://vimeo.com/api/v2/video/' + video_id + '.json',
        jsonp: 'callback',
        dataType: 'jsonp',
        success: function(data){
            var thumbnail_src = data[0].thumbnail_large;
            $('#thumb_wrapper').append('<img src="' + thumbnail_src + '"/>');
        }
    });
</script>

<div id="thumb_wrapper"></div>

Solution

  • Try this:-

    Assuming the div with id already exists.

      success: function(data){
    
                  $('<a/>',{
                     href:data[0].url,
                     text:data[0].title }).append(
                  $('<img/>' ,{
                     src:data[0].thumbnail_large
                  })
                  )
                  .appendTo('#'+data[0].id)
            }
    

    If the div with id doesnot exist:-

         success: function(data){
    
                  $('<a/>',{
                     href:data[0].url,
                     text:data[0].title })
                  .append(
                     $('<img/>' ,{
                     src:data[0].thumbnail_large
                     })
                  ).appendTo($('<div/>',{
                     id:data[0].id,
                     class:'vimeo'
    
                   }))
                   .appendTo('.someContainer');
            }
    

    Fiddle