Timer is not working when you call using class name in js

Viewed 99

My timer is not working. Here is the code.

var minutesLabel = document.getElementsByClassName('lol')[0].innerText;
    var secondsLabel = document.getElementsByClassName('lol1')[0].innerText;
    setInterval(setTime, 1000);
    
    function setTime() {
      ++totalSeconds;
      secondsLabel.innerHTML = pad(totalSeconds % 60);
      minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
    }
    
    function pad(val) {
      var valString = val + "";
      if (valString.length < 2) {
        return "0" + valString;
      } else {
        return valString;
      }
    }
<label class="lol" id="minutes">00</label>:<label class="lol1" id="seconds">00</label>

I have been trying to call it using the class name but i don't get it why it's not working

2 Answers

Try like this.

You have many mistakes in your code

  1. You haven't definefed totalSeconds
  2. you have defined minutesLabel like this var minutesLabel = document.getElementsByClassName('lol1')[0].innerText; and inside setTime function you used as minutesLabel.innerHTML. which is wrong.
  3. You have swapped mins and secs calculation

var min = document.getElementsByClassName('lol')[0];
var sec = document.getElementsByClassName('lol1')[0];
setInterval(setTime, 1000);
var totalSeconds = 0;
function setTime() {
  ++totalSeconds;
  sec.innerText = pad(totalSeconds % 60);
  min.innerText = pad(parseInt(totalSeconds / 60));
}

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}
<label class="lol" id="minutes">00</label>:<label class="lol1" id="seconds">00</label>

Few changes:

  • Initialize totalSeconds before an increment
  • I suggest you use document.getElementById
  • Using .innerText returns element value, but you need DOM element and its methods.

    var minutesLabel = document.getElementById('minutes');
    var secondsLabel = document.getElementById('seconds');
    var totalSeconds = 0;
    
    setInterval(setTime, 1000);
    
    function setTime() {
      ++totalSeconds;
      secondsLabel.innerText = pad(totalSeconds % 60);
      minutesLabel.innerText = pad(parseInt(totalSeconds / 60));
    }
    
    function pad(val) {
      var valString = val + "";
    
      if (valString.length < 2) {
        return "0" + valString;
      } else {
        return valString;
      }
    }
    
Related