Created
November 16, 2024 16:13
-
-
Save bronze/57e949b3ca4edf9c826f0a9d5a5d0fa4 to your computer and use it in GitHub Desktop.
YouTube Video with Timed Text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>YouTube Video with Timed Text</title> | |
<style> | |
.highlight { | |
display: block; | |
background-color: yellow; | |
color: red; | |
padding: 10px; | |
border-radius: 5px; | |
font-weight: bold; | |
} | |
.timed-text { | |
display: none; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="player"></div> | |
<p class="timed-text" data-time="300">5 minutes</p> | |
<p class="timed-text" data-time="600">10 minutes</p> | |
<script src="https://www.youtube.com/iframe_api"></script> | |
<script> | |
let player; | |
let paragraphs = document.querySelectorAll(".timed-text"); | |
function onYouTubeIframeAPIReady() { | |
player = new YT.Player("player", { | |
height: "360", | |
width: "640", | |
videoId: "KSCjl_VIdak", // Replace with your video ID | |
events: { | |
onReady: onPlayerReady, | |
onStateChange: onPlayerStateChange, | |
}, | |
}); | |
} | |
function onPlayerReady(event) { | |
event.target.playVideo(); | |
} | |
function onPlayerStateChange(event) { | |
if (event.data == YT.PlayerState.PLAYING) { | |
checkTime(); | |
} | |
} | |
function checkTime() { | |
let currentTime = player.getCurrentTime(); | |
paragraphs.forEach((paragraph) => { | |
let triggerTime = parseFloat(paragraph.getAttribute("data-time")); | |
if (currentTime >= triggerTime && currentTime < triggerTime + 1) { | |
paragraph.classList.add("highlight"); | |
} else { | |
paragraph.classList.remove("highlight"); | |
} | |
}); | |
setTimeout(checkTime, 100); // Check every 100 milliseconds | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment