要件に基づいて、HTML、CSS、JavaScriptを改変します。ただし、この環境ではインターネット接続が制限されているため、YouTube APIへの接続ができません。そのため、このコードはあくまでローカル環境での利用を想定しています。
また、YouTube APIを使用するためにはAPIキーが必要です。APIキーはGoogle Cloud Consoleから取得できます。APIキーを取得したら、以下のコード内の YOUR_API_KEY
の部分を自身のAPIキーに置き換えてください。チャンネルIDも同様に、取得したいチャンネルのIDを YOUR_CHANNEL_ID
の部分に置き換えてください。
さらに、YouTubeの画像が youtube.png
という名前で同じディレクトリに存在することを前提としています。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock and YouTube Info</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="content">
<div id="clock" class="light">
<div class="display">
<div class="digits"></div>
</div>
</div>
<div id="youtube" class="light" style="display: none;">
<img src="youtube.png" alt="YouTube">
<div id="subscribers"></div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript:
var apiKey = 'YOUR_API_KEY';
var channelId = 'YOUR_CHANNEL_ID';
window.onload = function () {
var clock = document.querySelector('#clock');
var youtube = document.querySelector('#youtube');
var subscribers = document.querySelector('#subscribers');
var isClockVisible = true;
setInterval(function () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var time = pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
clock.textContent = time;
if (seconds % 20 < 10) {
if (!isClockVisible) {
clock.style.display = 'block';
youtube.style.display = 'none';
isClockVisible = true;
}
} else {
if (isClockVisible) {
fetch('<https://www.googleapis.com/youtube/v3/channels?part=statistics&id=>' + channelId + '&key=' + apiKey)
.then(response => response.json())
.then(data => {
subscribers.textContent = data.items[0].statistics.subscriberCount;
});
clock.style.display = 'none';
youtube.style.display = 'flex';
isClockVisible = false;
}
}
}, 1000);
};
function pad(number) {
return ('0' + number).slice(-2);
}
CSS:
body {
background: #000;
color: #fff;
font-family: 'Share Tech Mono', monospace;
font-size: 50px;
text-align: center;
padding-top: 200px;
}
#content {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#clock, #youtube {
position: relative;
width: 50%;
text-align: left
}
.display {
text-align: center;
padding: 70px 0 100px 0;
}
#youtube img {
width: auto;
height: 80px;
}
#subscribers {
text-align: center;
margin-left: 20px;
}