index.html:
<!DOCTYPE html>
<html>
<head>
<title>YouTube Trending Videos</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>YouTube Trending Videos</h1>
<div id="videoList"></div>
<script src="https://www.google.com/jsapi"></script>
<script src="script.js"></script>
</body>
</html>
style.css:
body {
text-align: center;
margin-top: 50px;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
}
#videoList {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.videoItem {
width: 300px;
margin: 10px;
}
.videoItem img {
width: 100%;
height: auto;
}
.videoItem h2 {
margin: 10px 0;
}
.videoItem p {
color: #888;
}
script.js:
google.load("client", "1", {
callback: initialize
});
function initialize() {
gapi.client.setApiKey("YOUR_YOUTUBE_API_KEY");
gapi.client.load("youtube", "v3", function() {
searchTrendingVideos();
});
}
function searchTrendingVideos() {
var request = gapi.client.youtube.videos.list({
part: "snippet",
chart: "mostPopular",
regionCode: "US",
maxResults: 10
});
request.execute(function(response) {
var videoList = response.result.items;
displayVideos(videoList);
});
}
function displayVideos(videos) {
var videoListDiv = document.getElementById("videoList");
videos.forEach(function(video) {
var videoItem = createVideoItem(video);
videoListDiv.appendChild(videoItem);
});
}
function createVideoItem(video) {
var videoItemDiv = document.createElement("div");
videoItemDiv.classList.add("videoItem");
var thumbnailUrl = video.snippet.thumbnails.medium.url;
var videoUrl = "https://www.youtube.com/watch?v=" + video.id;
var thumbnailImg = document.createElement("img");
thumbnailImg.src = thumbnailUrl;
var titleH2 = document.createElement("h2");
titleH2.textContent = video.snippet.title;
var channelP = document.createElement("p");
channelP.textContent = "Channel: " + video.snippet.channelTitle;
var linkA = document.createElement("a");
linkA.href = videoUrl;
linkA.textContent = "Watch on YouTube";
videoItemDiv.appendChild(thumbnailImg);
videoItemDiv.appendChild(titleH2);
videoItemDiv.appendChild(channelP);
videoItemDiv.appendChild(linkA);
return videoItemDiv;
}
Make sure to replace "YOUR_YOUTUBE_API_KEY" in the initialize function with your actual YouTube Data API key.
In this example, the index.html file sets up the basic structure of the page and includes the necessary scripts. The style.css file contains the styles for the video list and its items. The script.js file initializes the YouTube Data API, performs a search for trending videos, and displays the results on the page.
0 Comments