Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  84] [ 4]  / answers: 1 / hits: 25002  / 7 Years ago, thu, june 8, 2017, 12:00:00

How can I have the time variable's contents displayed as the content property in my CSS?



JavaScript:



function clock(){
var d = new Date();
var hour = d.getHours();
var min = d.getMinutes();
var time = hour + : + min;
}


CSS:



.screen{
position: absolute;
height: 75%;
width: 75%;
background: #98E8EE;
top: 11.5%;
left: 12.5%;
}

.screen::after{
color: #F9F5F4;
font-size: 40px;
content: ;
font-family: Arial;
margin-left: 36.5px;
top: 20px;
position: relative
}



More From » css

 Answers
5

I'm not sure wether that's the best way to achieve what you want to do, as you could also use a container element and change its content directly:





const screenContentElement = document.getElementById('screen__content');

function pad(value) {
const str = value + '';

return str.length === 2 ? str : '0' + str;
}

function clock(){
var d = new Date();

return pad(d.getHours())
+ ':' + pad(d.getMinutes())
+ ':' + pad(d.getSeconds());
}

setInterval(() => {
screenContentElement.innerText = clock();
}, 1000);

#screen {
font-family: Arial, sans-serif;
position: relative;
height: 100%;
width: 100%;
background: #98E8EE;
text-align: center;
padding: 2rem 0;
}

#screen__content {
color: #F9F5F4;
font-size: 40px;
}

<div id=screen class=screen>
<span id=screen__content></span>
</div>





However, regarding the code you provided, to dynamically change the value of a content property in a CSS pseudo-element you can use the attr() CSS function together with a data-* attribute:





const screenElement = document.getElementById('screen');

function pad(value) {
const str = value + '';

return str.length === 2 ? str : '0' + str;
}

function clock(){
var d = new Date();

return pad(d.getHours())
+ ':' + pad(d.getMinutes())
+ ':' + pad(d.getSeconds());
}

setInterval(() => {
screenElement.dataset.time = clock();
}, 1000);

#screen {
font-family: Arial, sans-serif;
position: relative;
height: 100%;
width: 100%;
background: #98E8EE;
text-align: center;
padding: 2rem 0;
}

#screen::before {
color: #F9F5F4;
font-size: 40px;
content: attr(data-time);
}

<div id=screen></div>




[#57520] Wednesday, June 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kurtisl

Total Points: 559
Total Questions: 110
Total Answers: 97

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;