Reputation: 39
So I am trying to make an html header which automatically changes the number on the header countdown style. I have a working javascript variable which returns the days until my event. How can I pull the number calculated by the variable "daysUntil" into a span id called countdown in html page?
I searched for a solution and found a few answers regarding getElementById but was unsure how to implement it. I am JUST barely learning so thanks in advance if its a really basic question!
<!DOCTYPE html>
<head>
<title>Countdown</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var d1 = new Date(); //"now"
var d2 = new Date("2016/11/28") // some date
var diff = Math.abs(d2-d1)/(1000*60*60*24);
var daysUntil = Math.ceil(diff)
</script>
</head>
<body>
<div class="nav" id="top">
<ul>
<li><a href="/">COUNTDOWN</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="connect.html">Connect with Me</a></li>
</ul>
</div>
<div class="clearfix" id="content">
<div class="left">
<h1>T Minus <span id="countdown"></span>days!</h1>
<!-- The rest of the code is omitted-->
Upvotes: 2
Views: 68
Reputation: 6694
You have to put your <script>
after your countdown element.
...
<div class="left">
<h1>T Minus <span id="countdown"></span>days!</h1>
<script>
var d1 = new Date(); //"now"
var d2 = new Date("2016/11/28") // some date
var diff = Math.abs(d2-d1)/(1000*60*60*24);
var daysUntil = Math.ceil(diff);
var countdown = document.getElementById('countdown');
countdown.textContent = daysUntil + ' ';
</script>
</body>
</html>
Upvotes: 0
Reputation: 6419
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
This is the way to go, as well, as innerText
and innerHTML
.
The simple example would go as follow
document.getElementById('countdown').textContent = daysUntil.toString()
Upvotes: 4