big picture
big picture

Reputation: 301

Can Javascript detect when an embedded Youtube video has ended?

I have a div containing a video. The background of the div features a fake "play" button, which I've designed to use as the play button instead of Youtube's standard video "play" button. The video is initially set to "display:none".

I've deployed the code below so that when you click on the div, the div disappears and the video now displays and begins to play.

How can I edit the code so that when the video has finished playing, the video disappears and the div re-appears?

<div  class="videodiv" this.style.cursor='pointer'; 
onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; 
this.style.display='none'; "></div>
<div  class="youtubevid" id="thevideo" style="display: none;"><object width="420" 
height="160"><param name="movie" value="//www.youtube.com/v/vIdeoUrl?
 hl=en_US&amp;version=3&amp;rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1">
</param><param name="allowFullScreen" value="true"></param><param 
name="allowscriptaccess" value="always">
</param><embed src="//www.youtube.com/v/vIdeoUrl?
hl=en_US&amp;version=3&amp;rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" 
type="application/x-shockwave-flash" width="420" height="160" 
allowscriptaccess="always" allowfullscreen="true"></embed></object></div>

Upvotes: 1

Views: 7752

Answers (2)

user3117575
user3117575

Reputation:

Take a look in the API, it seems there is events.

player.addEventListener('onStateChange', function(e) {
   if (e.data === 0) {
     // If state is 0 (ended), do something
   }
});

Also, on the side note:

It looks like your YouTube video needs to be embed via JavaScript for events. To do so,

Upvotes: 2

happyvirus
happyvirus

Reputation: 286

Here's what you're looking for:

http://jsfiddle.net/7Gznb/

// when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) {            
            alert('done');
          //do something here

        }

That's the Youtube API by the way

Upvotes: 3

Related Questions