2

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

Thank you so much! I see you added a space there in the textContent + ' ' which I will just add in the h1 itself for simplicity. This was extremely helpful, especially the jsbin link!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.