Execute Javascript Function When Youtube Video Is Played (using Youtube Api)
I'm embedding a youtube video on my page using the following code:
Below code demonstrates and executes JS function using enablejsapi in iframe -
<!doctype html><html><body><iframeid="ytplayer"type="text/html"width="640"height="390"src="https://www.youtube.com/embed/YtF6p_w-cSc?autoplay=1&controls=0&enablejsapi=1"frameborder="0"></iframe><script>// Load the IFrame Player API code asynchronously.var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and// YouTube player after the API code downloads.var player;
functiononYouTubePlayerAPIReady() {
player = newYT.Player('ytplayer', {
height: '390',
width: '640',
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
myFunction();
}
}
}
});
}
functionmyFunction() {
alert("I am an alert box!");
}
</script></body></html>Here's JSFiddle
As per the above code JS function will be called once the playerstate is PLAYING. Hope this will help you and you are looking for the same. Also, please let me know if you have any questions.
Thanks..!
Post a Comment for "Execute Javascript Function When Youtube Video Is Played (using Youtube Api)"