Reputation: 309
I have created a button that pauses and plays a youtube video on click. I am trying to check if the video is already paused if so play, if its playing then pause. isPaused is not a function. What is the function I am looking for?
document.getElementById("playButton").addEventListener('click', function (event) {
if(!!player.isPaused()){
player.playVideo();
}
else {
player.pauseVideo();
}
});
Upvotes: 2
Views: 3896
Reputation: 47
Based on your requirements, you should use the player.getPlayerState()
function of the YouTube Player API, it returns the playback status of the player as:
So, your code should be updated as:
document.getElementById("playButton").addEventListener('click', function (event) {
if(player.getPlayerState()==1){ //Returns true if video is playing
player.pauseVideo();
}else{
player.playVideo();
}
});
Upvotes: 0
Reputation: 2575
Without mode details about your HTML controls, I think you're using a HTML element for control the reproduction (play) and pause functionality of a video.
If so, in the onPlayerStateChange
function, you have to set the logic as follows:
// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
// If the video is PLAYING, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will be paused.
if (event.data == YT.PlayerState.PLAYING) {
document.getElementById('playButton').innerHTML = 'Pause';
// Set the onclick event to the button for pause the YouTube video.
document.getElementById('playButton').onclick = function() {
player.pauseVideo();
};
}
// If the video is PAUSED, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will resume the video = continue playing the video.
if (event.data == YT.PlayerState.PAUSED) {
document.getElementById('playButton').innerHTML = 'Play';
document.getElementById('playButton').onclick = function() {
player.playVideo();
};
}
}
This function was modified from the available sample code in the YouTube Player API documentation.
Here is a working jsfiddle example.
Upvotes: 2