0

Hey I am new to coding and I'm working on a new chrome App. So far, I am trying to make a button that counts when you click on it. For some reason it's not working. Here's the HTML:

var button = document.getElementById("button"),
   count = 0;
   button.onclick = function() {
    count += 1;
    button.innerHTML = "Button: " + count;
  };
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1> This is a "Button" (I think) </h1>
    <p> (Or is it?) </p>
    <button id="button"> Button: 0 </button>
</body>
</html>
  
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
  • 1
    You should get the reference to the button element first by defining `var button = document.getElementById("button")`. You can then add event listener for the button element but your function definition is also wrong – Ozgur Sar Dec 01 '20 at 16:25
  • actually if I run your code it seems to work. What is exactly not working? – Lelio Faieta Dec 01 '20 at 16:43

2 Answers2

0

You have to wait until the DOM is loaded. Use the window.onload event:

window.onload = function() {
  var count = 0;
  const button = document.getElementById('button');
  button.onclick = function() {
    count += 1;
    button.innerHTML = "Button: " + count;
  };
};

Edit: I also just noticed you're not including your script in your HTML.

Dean James
  • 2,491
  • 4
  • 21
  • 29
0

Your missing a variable type on your count.

You want make sure your button has some kind of text inside of it before you actually start incrementing it.

Lastly you need to get the element from the html with a "document.getElementById("id_goes_in_here")

Try this instead.

document.getElementById("button").innerHTML = ` `; //Make sure to actually pull from your element in the html with this.

let count = 0;
button.innerHTML="Button " + count
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
Pablo Vahanian
  • 171
  • 1
  • 3