E Coder E Coder - 26 days ago 8
Javascript Question

why this simple javascript code about stopwach not working?

I wrote some very simple code the should represent a stopwatch with two buttons where clicking start should start counting upwards from 0 with 1 second delay.

However, when I click nothing changes. Where is my mistake?



"use strict";
var s = 1;

function mf() {
setInterval(function() {
document.getElementById("#sw").innerText = ++s;
}, 1000);
}

<div id="sw">0</div>
<input type="button" value="Start" name="start" onlick="mf" />
<input type="button" value="Stop" name="stop" />




Answer

You have two issues:

1): You're using

onlick="mf"

However, it should be:

onclick="mf();"

2): You used a # in your 'getElementByID'. This isn't jQuery- use

document.getElementById("sw")

Working Answer

"use strict";
 var s = 1;

  function mf() {
  setInterval(function() {
    document.getElementById("sw").innerText = s++;
   }, 1000);
 }
<div id="sw">0</div>
<input type="button" value="Start" name="start" onclick="mf();" />
<input type="button" value="Stop" name="stop" />

Your errors:

    document.getElementById("#sw").innerText = ++s;

should be

    document.getElementById("sw").innerText = s++;

Remove the #, and use s++, not ++s.

 <input type="button" value="Start" name="start" onlick="mf" />

That code has 2 errors: onlick and mf. Onlick isn't supported by all browsers yet (xD). Use onclick instead. Also, include the parameters, so mf()

Comments