Reputation: 59
I'm a beginner for javascript and HTML. and now working on my assignment from an online course. I'm currently making 3 minutes timer using HTML, CSS, and javascript. I borrowed javascript code form online and changing some codes to understand what's written in javascript. I have two questions...
one is when I put addEventListener('click', startTimer(), false); it just doesn't seem to work properly, and more like it's already triggering function in the javascript file. so I want to know why it's happening.
second is that innerHTML is not working. I tried to put document.getElementsByClassName('start').innerHTML = "START"; in javascript file, but I don't see 'START' on the web page. I don't actually need to insert innerHTML for START button but I tried to change other HTML part using innerHTML it's not working so I wonder why that's happening.
does somebody know how to make them work?
thank you!
document.getElementById('timer').innerHTML = "03" + ":" + "00";
document.getElementsByClassName('start').innerHTML = "START";
var start = document.getElementsByClassName('start');
start.addEventListener('click', startTimer(), false);
var stop = document.getElementsByClassName('stop');
stop.removeEventListener('click', startTimer(), false);
var reset = document.getElementsByClassName('reset');
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
//if(m<0){alert('timer completed')}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
<!DOCTYPE html>
<html class="no-js" lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title id="countdown-timer">3 Minutes Timer</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="timer-title">
<p>3 Minutes Timer</p>
</div>
<div class="timer-box">
<div class="timer-outer-display">
<div class="timer-display">
<div>
<p id="timer" ></p>
</div>
</div>
</div>
<div class="button">
<button class="start"></button>
<button class="stop">STOP</button>
<button class="reset">RESET</button>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Upvotes: 1
Views: 342
Reputation: 15
You forgot to indicate the element number of the collection...
var start = document.getElementsByClassName('start')[0];
NB: Square brackets.
Upvotes: 1