Running a JS function with an HTML button

This short tutorial shows how to run a function written in JavaScript when a button is pressed.

The Code

<html>
  <body>
    <button id="btn1" onclick="buttonClick()">Click on me</button><br>
    <p id = "result"></p>
    <script>
      function buttonClick() {
        document.getElementById('result').innerHTML = 'The button was clicked.';
      }
    </script>
  </body>
</html>

How the code works

The HTML code has three tags:

  • <button> – which displays a button. Two properties are set for the button: id, which is the button’s name, and onclick, which defines what function should be run when the button is pressed.
  • <p> – which displays a paragraph, initially blank. It will be used by the JavaScript function to display text after the button is pressed.
  • <script> – contains the JavaScript code.

The JavaScript code defines one function, called buttonClick. The function contains a single line of code, which is run when the button is pressed.

The function displays the sentence “The button was clicked.” in the paragraph with id of “result”. This will appear just below the button.

Comments

Leave a comment