Karissa Martin Karissa Martin - 1 month ago 8
HTML Question

Use value of javascript variable within html page

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-->

Answer

You have to put your <script> after your countdown element.

See live demo

... 
<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>