Palmetto Innovation Center

JavaScript Calculator

JavaScript is a programming language used to provide functionality to web pages.

So far, we have created the HTML to define what will be displayed in the browser window: a button. We defined the CSS so the browser knows how the button should look. Now, we are going to write the JavaScript code to make the button perform an action.

Step 3 - Lesson

Instructions

  1. In your index.html file,
    1) add the <script>...</script> code below to the <head> section,
    2) add this code to the <button> element as shown below:
    onClick="calculatorButtonClicked('0')" Accessibility users can access the full code as text in the "Step 3 Resources - HTML Markup in the index.html File" section at the bottom of this page.

    JavaScript code example
  2. Click the Save button to save your index.html file.

    Hint: Press the Ctrl + S keys to save your file quickly.

  3. Click the Run button and check whether your button behaves like the sample shown in the Results section below. You should see a window alert displaying "0".

  4. Go to Step 4: Include Files

JavaScript Code

<script>

  function calculatorButtonClicked(buttonValue) {

    alert(buttonValue);

  }

</script>

Result

Click the button to see what happens.

Step 3 - Resources

Explanation

  1. onClick="calculatorButtonClicked('0')"

    The JavaScript onClick event triggers its associated function. In this case, it calls a JavaScript function named calculatorButtonClicked, passing a parameter of 0.


  2. <script>

    The HTML <script> element is a child of the <head> element. It indicates to the browser that its contents are JavaScript code.


  3. function calculatorButtonClicked(buttonValue) {

    JavaScript functions are blocks of code that provide functionality. In this case, when the user clicks the 0 button, the JavaScript function named calculatorButtonClicked is invoked and executed.

      function calculatorButtonClicked(buttonValue) {        // the start of the function with a parameter named "buttonValue"

        alert(buttonValue);            // this displays the alert message

      }            // end of the function


HTML Markup in the index.html File

The HTML markup in your index.html file should match the sample below:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>My Calculator</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
      .buttonStyle {
        width: 50px;
        height: 50px;
        font-weight: bold;
        font-size: 1em;
        margin-bottom: 0.4em;
        margin-right: 0.2em;
      }
    </style>

    <script>

      function calculatorButtonClicked(buttonValue) {

        alert(buttonValue);

      }

    </script>

  </head>
  <body>

    <button type="button" class="buttonStyle" onClick="calculatorButtonClicked('0')">0</button>

  </body>
</html>