0

i keep getting error said: Cannot set property 'innerHTML' of null.

i try to change innerHTML ->innerText. still not working.

what am i missing here???

  function countdown(minutes) {
          var seconds = 60;
          var mins = minutes
          function tick() {
              var counter = document.getElementById("timer");
              var current_minutes = mins-1;
              seconds--;
              counter.innerHTML = 
    current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
              if( seconds > 0 ) {
                setTimeout(tick, 1000);
              } else {
                if(mins > 1){
                  // countdown(mins-1);   never reach “00″ issue solved:Contributed by      
 Victor Streithorst    
                  setTimeout(function () { countdown(mins - 1); }, 1000);
              }
            }
        }
        tick();
    }        
    countdown(3);

html

   <div id="timer"></div>
4
  • 1
    your <div> isn´t rendered when your code is executed, you need to execute your code after pageload Commented Sep 22, 2014 at 7:00
  • Call the countdown function after the <div id="timer"></div>. Also you can use jQuery document ready if you wish to use jQuery. Commented Sep 22, 2014 at 7:00
  • You have some typos, fix them (missing ; and ,) Commented Sep 22, 2014 at 7:01
  • jsbin.com/fijikewotuwu/1/edit its working :) Commented Sep 22, 2014 at 7:09

1 Answer 1

1

You're calling countdown(), which calls tick(), which calls document.getElementById("timer"), before that element has even been parsed.

Try doing it like this:

<div id="timer"></div>
<script type="text/javascript">
function countdown(minutes) {
    var seconds = 60;
    var mins = minutes
    function tick() {
        var counter = document.getElementById("timer");
        var current_minutes = mins-1
        seconds--;
        counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if( seconds > 0 ) {
            setTimeout(tick, 1000);
        } else {

            if(mins > 1) {
                // countdown(mins-1);
                setTimeout(function () { countdown(mins - 1); }, 1000);
            }
        }
    }
    tick();
}

countdown(3);
</script>

In this case, order matters. You want to make sure the document has encountered that element before accessing it via the DOM.

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

Comments

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.