I want to run a function called stopSlide
whenever someone clicks the 'play' button on an embedded youtube video. Or even getting the function to run when they click anywhere inside the embedded video would work fine for me right now.
How can I do this?
Developers can use the iFrame API to programmatically create and interact with an Embed or with multiple Embeds in the same web app. The iFrame API includes methods that you can use to start playback, change the content rendering in an Embed, or stop playback.
Until and unless you have allow="autoplay;" in your iframe tag you wont be able to unmute the video. Add this attribute and further unMute function will work. Save this answer.
There is a YouTube JavaScript API that provides event callbacks.
There is, unfortunately, no way to directly detect a click event (at least I am not aware of any). You can, however, detect changes in the player state for which you can use onStateChange
.
First, you will need to enable the JS API in the player by embedding it by using a special URL:
http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1
Then you need to create an event handler function:
function player_state_changed(state) {
/* This event is fired whenever the player's state changes.
Possible values are:
- unstarted (-1)
- ended (0)
- playing (1)
- paused (2)
- buffering (3)
- video cued (5).
When the SWF is first loaded it will broadcast an unstarted (-1) event.
When the video is cued and ready to play it will broadcast a video cued event (5).
*/
if (state == 1 || state == 2) {
alert('the "play" button *might* have been clicked');
}
}
Lastly, you need to make sure that the handler gets called whenever the state of the movie changes:
document.getElementById('MY-PLAYER-ID').addEventListener('onStateChange', 'player_state_changed');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With