%%html
<html>
<head>
<title>YouTube Video Search and Player</title>
</head>
<body>
<h1>YouTube Video Search and Player</h1>
<!-- Search input -->
<input type="text" id="searchInput" placeholder="Search for videos">
<button id="searchButton">Search</button>
<!-- YouTube video container -->
<div id="player"></div>
<!-- Script to load YouTube Data API -->
<script>
// Replace 'YOUR_API_KEY' with your actual YouTube API key
const apiKey = 'AIzaSyDIXtWwfFj3rwlD7yaKvJIkqHjfWUdwG18';
// Load the YouTube Data API script
const script = document.createElement('script');
script.src = `https://apis.google.com/js/api.js`;
document.head.appendChild(script);
// Function to initialize the YouTube Data API
function init() {
gapi.client.init({
apiKey: apiKey,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"],
}).then(function () {
// Handle the search button click
const searchButton = document.getElementById('searchButton');
searchButton.addEventListener('click', searchVideos);
});
}
// Function to search for videos
function searchVideos() {
const searchInput = document.getElementById('searchInput');
const query = searchInput.value;
gapi.client.youtube.search.list({
q: query,
part: 'snippet',
type: 'video',
maxResults: 1, // Number of results to display
}).then(function (response) {
const videoId = response.result.items[0].id.videoId;
// Create and initialize the YouTube player with the found video
initializePlayer(videoId);
});
}
// Function to create and initialize the YouTube player
let player;
function initializePlayer(videoId) {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: videoId,
playerVars: {
'autoplay': 1,
'controls': 1,
},
});
}
</script>
<!-- Load the YouTube Data API client -->
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</body>
</html>
Youtube Player • 3 min read
Description
Fun Project