28

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?

1 Answer 1

38

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.
    }
});
7
  • hm, I added to my code, player.addEventListener("onStateChange", function(state) { if (state === 0) { alert('end'); } }); but event doesn't occur!
    – ihorko
    May 27, 2012 at 11:30
  • 1
    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
    – wong2
    May 27, 2012 at 11:46
  • 2
    state is an object. You have to check for state.data === 0 (I used &enablejsapi=1&version=3 in the iframe url) Oct 20, 2014 at 15:25
  • 3
    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.
    – Jo.
    Jul 29, 2015 at 15:34
  • 1
    Does anyone know if this is possible on a live stream aswell? Jan 30, 2018 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.