The code executed on click is:
function onClick() {
counter++;
}
As you can see, the counter is incremented but the screen is not refreshed. To fix this problem you could think of copying document.write(counter)
inside the function, but the first time the button is clicked document.write
overwrites the original HTML and the button disappears:
counter = 0;
document.write(counter);
function onClick() {
counter++;
document.write(counter);
}
<button onclick="onClick()">increase</button>
To refresh the screen properly you need to know what the DOM is. Roughly speaking, the DOM (Document Object Model) is an equivalent of your HTML document in the JavaScript world. Thanks to the DOM you can manipulate the HTML document using JavaScript.
Think of an HTML document as a tree with parent and child elements (for example <html>
has two children, <head>
and <body>
). The root of this tree is the document itself, and the first child of the document is the <html>
element. In the JavaScript world, the document can be found in a preexisting variable called document
. You can ask document
to find some descendant elements for you like so:
html = document.children[0];
buttons = document.getElementsByTagName("button");
You can also manipulate the elements one by one. For example, if you want to change the text inside the button, you can do it like so:
button = buttons[0]; // first button found in the tree
button.textContent = "counter plus plus";
Based on this knowledge, here is a possible solution to print the counter on click:
counter = 0;
function onClick() {
counter++;
var span = document.getElementById("counter");
span.textContent = counter;
}
<button onclick="onClick()">increment</button>
<span id="counter">0</span>
I suppose you can finish the job by yourself :-)