I want to create a string in JavaScript that gives the current time, but I want the hours, minutes, and seconds to be visibly divided by a colon. The pieces should be a different color than the numbers created with JavaScript.
Following the base I want to work with.
JS
var currentTime = document.getElementById('time');
function setTime() {
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
if (s < 10) {
s = '0' s;
}
if (m < 10) {
m = '0' m;
}
if (h < 10) {
h = '0' h;
}
currentTime.textContent = h ':' m ':' s;
}
setInterval(setTime, 100);
HTML
<h1 id="time"></h1>
CSS
#time {
margin-top: 7rem;
margin-bottom: 1rem;
font-size: 3.2rem;
color: #60D291;
}
CodePudding user response:
You can try this :
var currentTime = document.getElementById("time");
var span = document.getElementsByTagName("span");
function setTime() {
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
if (s < 10)
s = "0" s;
if (m < 10)
m = "0" m;
if (h < 10)
h = "0" h;
span[0].textContent = h;
span[1].textContent = " : " m;
span[2].textContent = " : " s;
span[0].style.color = "red";
span[1].style.color = "green";
span[2].style.color = "blue";
}
setInterval(setTime, 100);
#time {
margin: 1rem;
margin-top: 7rem;
font-size: 3.2rem;
color: #60D291;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#time {
margin: 1rem;
margin-top: 7rem;
font-size: 3.2rem;
color: #60D291;
}
</style>
</head>
<body>
<h1 id="time">
<span></span><span></span><span></span>
</h1>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could also separate each unit into spans so styling remains in CSS.
let hour = document.getElementById('hour');
let min = document.getElementById('min');
let sec = document.getElementById('sec');
function setTime() {
const date = new Date();
const s = date.getSeconds().toLocaleString('en-US', { minimumIntegerDigits: 2 });
const m = date.getMinutes().toLocaleString('en-US', { minimumIntegerDigits: 2 });
const h = date.getHours().toLocaleString('en-US', { minimumIntegerDigits: 2 });
hour.textContent = h ' :';
min.textContent= m ' :';
sec.textContent = s;
}
setInterval(setTime, 100);
#time {
margin: 1rem;
font-size: 3.2rem;
}
#hour {
color: red;
}
#min {
color: green;
}
#sec {
color: blue;
}
<h1 id="time">
<span id="hour"></span>
<span id="min"></span>
<span id="sec"></span>
</h1>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>