سؤال

I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...

I am stuck on the hover command. Can someone help me work it out please?

The page has 16 videos, this is the working code from the jsfiddle that contains 3 videos as an example.

http://jsfiddle.net/sebwhite/gpJN4/

VIDEO:

<iframe id="player" width="385" height="230" src="http://www.youtube.com/embed/erDxb4IkgjM?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0" frameborder="0" allowfullscreen></iframe>

JAVASCRIPT:

function onYouTubeIframeAPIReady() {
 player = new YT.Player('player', {
     events: {
         'onStateChange': onPlayerStateChange
     }
 });

onYouTubeIframeAPIReady();
function onPlayerStateChange(event) {
 if (event.data == YT.PlayerState.PLAYING) {
     player1.pauseVideo();
     player2.pauseVideo();
 }
هل كانت مفيدة؟

المحلول

UPDATED FIDDLE

Try this:

 var $$ = function(tagname) { return document.getElementsByTagName(tagname); }
    
 function onYouTubeIframeAPIReady() {
     var videos = $$('iframe'), // the iframes elements
         players = [], // an array where we stock each videos youtube instances class
         playingID = null; // stock the current playing video
     for (var i = 0; i < videos.length; i++) // for each iframes
     {
         var currentIframeID = videos[i].id; // we get the iframe ID
         players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
         // note, the key of each array element will be the iframe ID
         
         videos[i].onmouseover = function(e) { // assigning a callback for this event
             if (playingID !== currentHoveredElement.id) {
               players[playingID].stopVideo();
             }
             var currentHoveredElement = e.target;
             if (playingID) // if a video is currently played
             {
                 players[playingID].pauseVideo();
             }
             players[currentHoveredElement.id].playVideo();
             playingID = currentHoveredElement.id;
         };
     }
    
 }
 onYouTubeIframeAPIReady();

Fiddle:

http://jsfiddle.net/gpJN4/3/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top