javascriptjqueryhtmldom

How to make buttons that increment and decrement a value when clicked?


I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?

<body>
  <input type=button value="increment" onclick="button1()" />
  <input type=button value="decrement" onclick="button2()" />
  <script type="text/javascript">
    var x = 0
    document.write(x)

    function button1() {
      document.write(x++)
    }
    function button2(){
      document.write(x--)   
    }
  </script>
</body>

Solution

  • The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.

    Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.

    Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.


    document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.

    Moreover, use addEventListener instead of inline event listeners:

    var x = 0;
    var span = document.querySelector('span'); // find the <span> element in the DOM
    var increment = document.getElementById('increment'); // find the element with the ID 'increment'
    var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
    
    increment.addEventListener('click', function () {
      // this function is executed whenever the user clicks the increment button
      span.textContent = x++;
    });
    
    decrement.addEventListener('click', function () {
      // this function is executed whenever the user clicks the decrement button
      span.textContent = x--;
    });
    <button id="increment">increment</button>
    <button id="decrement">decrement</button>
    <span>0</span>

    As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.