Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
842 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...