jQuery: YouTube video slideshow

Creating a YouTube video slideshow with jQuery is exactly the same thing as creating any other jQuery slideshow. The only difference is that instead of divs or images we're dealing with the iframes used by YouTube to embed its videos in web documents. As you will see, there's nothing difficult with this. As usual, we start with our underlying markup first:

<div id="slideshow">

  <div id="slideshow-wrapper">
  
   <iframe width="425" height="349" src="http://www.youtube.com/embed/AMopwcXEDIk" frameborder="0" allowfullscreen></iframe>
   <iframe width="425" height="349" src="http://www.youtube.com/embed/1RhyQG9HJ7U" frameborder="0" allowfullscreen></iframe>
   <iframe width="425" height="349" src="http://www.youtube.com/embed/ba4a_HwXwnA" frameborder="0" allowfullscreen></iframe>
  
  </div>

</div>

Nothing strange, except for the iframes. Now our CSS:

#slideshow {
 width: 425px;
 height: 349px;
 position: relative;
 overflow: hidden;
 margin: 0 auto;
}

#slideshow-wrapper {
 width: 1275px;
 height: 349px;
 position: relative;
}

#slideshow-wrapper iframe {
 float: left;
 width: 425px;
 height: 349px;
}

Iframes have been left-floated so now they're normal block-level elements. With jQuery, we have first to store all the iframe left offsets into an array using a custom function and then create a simple timer that cycles through this array using a progressive index incremented each time the timer runs:

var getVideoPositions = function() {

  var offsets = [];
  
  $('iframe', '#slideshow-wrapper').each(function(i) {
  
    var left = $(this).position().left;
    offsets[i] = left;
  
  });
  
  return offsets;

};

$(function() {

  var wrapper = $('#slideshow-wrapper', '#slideshow');
  var len = $('iframe', '#slideshow-wrapper').length;
  var index = 0;
  var positions = getVideoPositions();
  
  var interval = setInterval(function() {
  
    index++;
    
    if(index == len) {
    
      index = 0;
    
    
    }
  
    wrapper.animate({
      left: - positions[index]
    }, 1500); 
  
  
  }, 1500);



});

You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.