I need help here please, I embed a YouTube video when a user watch the embed video for 30seconds I want the claim reward button to display then the rest action is left to livewire this is what I have tried and still after watching the video for 30 seconds nothing happened
<div class="p-3">
<div class="space-y-3">
<h2 class="font-bold">{{$video->title}}</h2>
<div class="relative rounded-lg overflow-hidden" style="padding-bottom: 56.25%;">
<iframe id="videoFrame" class="absolute top-0 left-0 w-full h-full rounded-lg" src="https://www.youtube.com/embed/{{$video->embed_code}}" frameborder="0" allowfullscreen></iframe>
</div>
<div id="claimButton" style="display: none;">
@if (!$claimed)
<button wire:click="claimReward" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
Claim Reward
</button>
@else
<div class="mt-2 text-green-500">Reward claimed</div>
@endif
</div>
</div>
</div>
Js
<script>
// Initialize YouTube Player API
var player;
// Function to initialize the player
function onYouTubeIframeAPIReady() {
player = new YT.Player('videoFrame', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
// Function to handle player state change
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
// Video has started playing, start tracking time
startTime = Date.now();
} else if (event.data == YT.PlayerState.ENDED) {
// Video has ended, check if user can claim reward
checkWatchTime();
}
}
// Function to check watch time and show the "Claim Reward" button
function checkWatchTime() {
const currentTime = Date.now();
const elapsedTime = (currentTime - startTime) / 1000; // Convert to seconds
if (elapsedTime >= 30 && !claimed) {
document.getElementById('claimButton').style.display = 'block';
}
}
</script>
<script src="https://www.youtube.com/iframe_api"></script>
I need help
2
Answers
You’ve debugged this and you have tested that the stateChanged function is being called, right? Then the way I recommend you do this is by setting a timeout, and clearing it if the user doesn’t watch for 30 seconds.
You need to initialize the YT.player on an empty div or an iframe with "enablejsapi" and "origin" being set in the src. Here’s a working snippet based on yours, using a div:
Here’s the documentation