Search code examples
jquerythumbnailsvimeo

Put Vimeo thumbnail URL into each same class div - jquery


I find a way on how to get the Vimeo thumbnail URL by jquery already. But my page will have more than one Vimeo video. Not sure how can I put the related thumbnail URL for its related div. I tried using "each" "var image as a set of image" .. but none of them seem working.

$(".video-container").each( function() {
  var iframe           = $(this).children('iframe');
  var iframe_src       = iframe.attr('src');
  
  if (iframe_src.indexOf("www.youtube.com") >= 0) {
    // alert('youtube');
  } else if (iframe_src.indexOf("player.vimeo.com") >= 0) {
    alert('vimeo');
    var vimeoVideoID = iframe_src.match(/vimeo\.com.*(\?v=|\/video\/)(.{9})/).pop();
    // alert(vimeoVideoID);

    $.getJSON('https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/' + vimeoVideoID, {
        format: "json",
        width: "640"
      },
      function(data) {
        // alert(data.thumbnail_url);
        $(".video-container").css( "background-image", "url('"+data.thumbnail_url+"')" );
      });
  }
});
.video-container{
width: 200px;
height: 100px;
background-repeat: no-repeat;
background-position: center;
background-size: 100%;
}

.video-container iframe{
width: 100%; 
height: auto;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <h4>Vimeo video 1</h4>
        <div class="video-container">
          <iframe width="750" height="420" src="https://player.vimeo.com/video/218830007" frameborder="0" title="Video Title"></iframe>
        </div>

      <h4>Vimeo video 2</h4>
        <div class="video-container">
          <iframe width="750" height="420" src="https://player.vimeo.com/video/548847228" frameborder="0" title="Video Title"></iframe>
        </div>


Solution

  • on this line u set the background image to every element with class .video-container

    $(".video-container").css( "background-image", "url('"+data.thumbnail_url+"')" );
    

    i would store "this" referrencing the current element with class .video-container

    $(".video-container").each( function() {
       var $self = $(this); 
    

    and on api success i would do

     $self.css( "background-image", "url('"+data.thumbnail_url+"')" );
    

    PS: Alternatively u can just use the params of jquery´s each like:

    $(".video-container").each(function(index,element){
       $(element).css(...)
    });