I'm embedding a youtube video on my page using the following code:
<iframe width="400" height="300" id="newvid" src="http://www.youtube.com/embed/url?modestbranding=1&showinfo=0&feature=player_embedded&fs=0&iv_load_policy=3&rel=0" frameborder="0"></iframe>
I'm trying to use the Youtube API, so a javascript function will be executed once user is playing the video, but the following code doesn't work, as I don't see any alert showing when clicking the video:
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('newvid', {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
myFunction();
}
}
}
});
}
</script>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
Below code demonstrates and executes
JS function
usingenablejsapi
iniframe
-Here's JSFiddle
As per the above code
JS function
will be called once theplayerstate
isPLAYING
. Hope this will help you and you are looking for the same. Also, please let me know if you have any questions.Thanks..!
It should be set up with a div container rather than selecting the iFrame. (This may not run correctly in the snippet container, however please try in your code).