Palmetto Innovation Center

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 do something.

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 seen 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.

  2. Click the Save Button to save your index.html file.

    Hint: press the ctrl + s keys for a shortcut to saving files.

  3. Click the Run button and check that your button behaves like the sample in the Results section below when clicked. You should see a window alert with 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 causes its value to be executed. In this case, it calls a JavaScript function named "calculatorButtonClicked" passing in a parameter of 0.


  2. <script>

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


  3. function calculatorButtonClicked(buttonValue){

    JavaScript functions are blocks of code that provide functionality. In this case, when the user clickes the 0 button, the JavaScript function named "calculatorButtonClicked" will be called and executed.

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

        alert(buttonValue);                               this displays the browser 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>