Event when YouTube video finished

60,017

Youtube has a JavaScript API: https://developers.google.com/youtube/js_api_reference

What you need is the onStateChange event, which will give you 0 when ended.

player.addEventListener("onStateChange", function(state){
    if(state === 0){
        // the video is end, do something here.
    }
});
Share:
60,017

Related videos on Youtube

ihorko
Author by

ihorko

Updated on December 25, 2020

Comments

  • ihorko
    ihorko over 3 years

    I have simple html code that plays YouTube video after click on the image:

    <body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
    
    <div id="ytapiplayer2" style="display:none;">
    <object width="1280" height="745">
    <param name="movie" value="http://www.youtube.com/v/kCfP003Btjw?fs=1&hl=en_US&rel=0&autoplay=1"></param>
    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/kCfP003Btjw?fs=1&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="1280" height="745"></embed>
    </object>
    
    </div>
    
    
    <img src="https://i.qmyimage.com/mgen/global/zGetImageNew.ms?args=%22shpimg4198.jpg%22,425,96,1" id="imageID" />
    <script type="text/javascript">
    $('#imageID').click(function() {
    $('#ytapiplayer2').show();
    $('#imageID').hide();
    });
    </script>
    </body>
    

    I need hide the video and show image back, after video finished play. How is it possible to implement?

  • ihorko
    ihorko almost 12 years
    hm, I added to my code, player.addEventListener("onStateChange", function(state) { if (state === 0) { alert('end'); } }); but event doesn't occur!
  • wong2
    wong2 almost 12 years
    perhaps you have to change the way you embed the video, see examples here: developers.google.com/youtube/js_api_reference#Examples and remember to load the api script
  • Kristóf Dombi
    Kristóf Dombi over 9 years
    state is an object. You have to check for state.data === 0 (I used &enablejsapi=1&version=3 in the iframe url)
  • Jo.
    Jo. over 8 years
    Note that the JavaScript API is now deprecated; it is recommended that you use the IFrame API: developers.google.com/youtube/iframe_api_reference which has similar methods for state change.
  • Victor Öhrström
    Victor Öhrström about 6 years
    Does anyone know if this is possible on a live stream aswell?
  • Manoj Patidar
    Manoj Patidar almost 4 years
    @VictorÖhrström did you know how to get end livestream event of youtube.
  • Victor Öhrström
    Victor Öhrström almost 4 years
    @ManojPatidar No when i was in need of this youtube didn't have any support for this, i don't know if they have added it later.