Part 3 – JavaScript and HTML Connections

Table of Contents

  1. Introduction
  2. Adding a button with JavaScript Action
    1. Example Using Buttons and JavaScript
  3. Using Input Forms with JavaScript Function
  4. Embedding a Video
  5. Quiz over HTML and JavaScript
  6. Not All Browsers Handle Scripting the Same Way
  7. Write a MadLib
  8. Create a Calculator
  9. Doing Better in School Takes Grit
  10. Putting JavaScript in its own file


This section expects you to have already created a Third Web Page in your Web Site. You have already created the framework for the page. All that is needed now is to add elements that allow communication between HTML elements and JavaScript functions.

Adding a button with JavaScript Action

This section explains how to add a button and the ability to have it do something useful. In this case, it generates random emotions from a list. In this example, HTML calls a JavaScript function (surrounded by &lt:script>…</script> tags). The JavaScript can modify any entity that has an attached id. The code to be added to the first section of Page 3 is:

            <h2><a name="Buttons" id="Buttons"></a>Using Buttons and JavaScript</h2>
            <p>Click the button to trigger a function that will output a different emotion in a q element
            with id="changing".</p>

            <button onclick="myFunction()">Click me</button>

            <p> I am feeling <q id="changing">Neutral</q> today.</p>

            <p id="num">0</p>

                function myFunction() {
                    mood = ["Happy", "Bodacious", "Sad", "Joyous", "Curious", "Neutral", "Grateful",
                        "Confused", "Intelligent", "Hungry", "Grumpy", "Overwhelmed"];
                    var moodIndex = Math.floor(Math.random() * mood.length);
                    document.getElementById("num").innerHTML = moodIndex;
                    var moodElem = mood[moodIndex]
                    document.getElementById("changing").innerHTML = moodElem;

Example Using Buttons and JavaScript

This is the example of the above code. Click the button to trigger a function that will output a different emotion in a q element with id=”changing”.

I am feeling Neutral today.


A Few Things to Notice

  1. JavaScript is an object oriented (OO) language. It has built-in libraries, like the math library which has methods (functions that do something) and attributes (storage for important information).
  2. The main obvious difference between methods and attributes. The obvious difference is that methods end with (), a parameter list with zero or more parameters (values that are passed into the method. Attributes take not parameters, thus do not need the () parameter list.
  3. Make sure your function name matches the function your button is calling. This includes all capitalization and special characters. The name must be a single word with no spaces.
  4. Math.floor() truncates a number to its base integer
  5. Math.random() returns a random number between 0 and 1. To have a number in the range you would like, the returned random number must be multiplied by the list's length.
  6. The name and id are used for similar purposes, like in identifying labels within an HTML file. That is why I use both for tagging headings. In the next section, you will see that the name tag is used for grouping radio button or checkbox lists while id is used to specify specific forms.

Using Input Forms with JavaScript Action

This additional code goes at the very end of your HTML page 3. It shows you how to use a form with input boxes, radio buttons (where you can choose only one item from a list), and check boxes (where you can choose multiple items from a list. The Java code reads the information you entered and writes a story in the paragraph below the form.

            <h2><a name="InputForms-JS" id="InputForms-JS"></a>Using Input Forms</h2>

            Here we are creating a table with four forms. The first one is to gather the name of the person,
            the second is to gather their position, the third is to gather their modes of transportation, and
            the last is to submit the entire information.<br><br>

            <table width="80%" align="center">
                        <th>Input Form/Name</th>
                        <th>Radio Buttons/Position</th>
                        <th>Check Boxes/Transportation</th>
                        <th>Submittal Button</th>
                        <td align="center">
                            <form id="nameInfo">
                                First Name:<br>
                                <input type="text" name="firstName"><br>
                                Last Name:<br>
                                <input type="text" name="lastName"><br>
                                E-Mail Address:<br>
                                <input type="email" name="e-mail">
                            <form id="positionInfo">
                                <input type="radio" name="position" value="a Middle School Student" checked> Middle School Student<br>
                                <input type="radio" name="position" value="an High School Student"> High School Student<br>
                                <input type="radio" name="position" value="a Teacher"> Teacher<br>
                                <input type="radio" name="position" value="an Administrator"> Administrator<br>
                                <input type="radio" name="position" value="some other position"> Other
                            <form id="transportationInfo">
                                <input type="checkbox" name="transportation" value="walk"> I walk to school<br>
                                <input type="checkbox" name="transportation" value="ride in car"> I ride in a car<br>
                                <input type="checkbox" name="transportation" value="bike"> I ride a bike<br>
                                <input type="checkbox" name="transportation" value="board"> I ride a skateboard<br>
                                <input type="checkbox" name="transportation" value="pogostick"> I hop on a pogostick<br>
                                <input type="checkbox" name="transportation" value="drive a car"> I drive a car<br>
                        <td align="center">
                                <input type="button" onclick="mySubmittal()" name="Submit" value="Submit">

            <h3>The Story</h3>

            <p id="storyTime">Just Wait!</p>

                function mySubmittal() {
                    document.getElementById("storyTime").innerHTML = "Make sure you checked a position";
                    var x = document.getElementById("nameInfo");
                    var str = "Welcome " + x.elements[0].value + " " + x.elements[1].value + "! We can reach you at: " + x.elements[2].value;
                    str += "<br>You are at CEC as " + document.querySelector('input[name="position"]:checked').value;
                    var entries = 0;
                    var trs = document.forms['transportationInfo'].elements['transportation'];
                    str += "<br>You ";
                    trsLen = trs.length;
                    for (var i = 0; i < trsLen; i++) {
                        if (trs[i].checked) {
                            if (entries != 0) str += "<b>//</b>";
                            str += trs[i].value;
                    if (entries == 0) str += "don't go";
                    str += " to school.<br> You have ";
                    str += entries.toString();
                    str += " ways to get to school.";
                    document.getElementById("storyTime").innerHTML = str;

Things to consider when using forms

Forms are a very useful tool for gathering information. In this example, I use three different types of forms, but a Submit button. I put these forms into a table so that the forms can be organized across the page. Some things to consider include:

  1. Arrange your forms in a way that makes sense. You can include all of the information in one form that will have one section below the previous section in the same column. I use a table so that I can arrange the forms horizontally instead of vertically.
  2. Input forms, the first form panel, are addressed by index instead of by name.
  3. Radio buttons and checkboxes are similar, in that each allows multiple choices. Radio buttons allow only one choice, but checkboxes can have multiple selections.
  4. Radio buttons always need a default (checked) value.
  5. In the JavaScript, I count the number of items checked in the checkbox list and do something different for the first item and also if no items are checked. Take these two instances into account when you are designing how to use a checkbox list.
  6. I did not use type="submit" for the Submit button because it resets all fields in the forms when I pushed the Submit button. The type="button" acts like a normal push button, which is the behavior I wanted for this button.

Using Input Forms with JavaScript Handling the Entries

Here we are creating a table with four forms. The first one is to gather the name of the person, the second is to gather their position, the third is to gather their modes of transportation, and the last is to submit the entire

Input Form/Name Radio Buttons/Position Check Boxes/Transportation
First Name:

Last Name:

E-Mail Address:
MS Student
High School Student
I walk to school
I ride in a car
I ride a bike
I ride a skateboard
I hop on a pogostick
I drive a car

The Story

Just Wait!

Embedding a Video

This is purely HTML code, but it fits more with having the website do something. There are many videos that we might want to add that enhance what we are writing. I personally like TED talks and use several of them for my web blog. It is simple to embed a YouTube video. One way is to use an iframe command. If you go to the Share command at the bottom of the YouTube page. At the bottom of the pop-up dialog box is the word EMBED, press it and it brings up the embed code. Copy the code and put it into your code. The code would look at:

<iframe src="" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

It produces an inclusion:

Quiz over HTML and JavaScript

You will create a fourth webpage that looks as much as possible like webpage 3. It will include the following:

  1. One <head> section with a <title> and link to your css file.
  2. One <body> section with one <div> section included. the <div> definition includes the background picture for the page.
  3. an <header> section that contains the title to be displayed on the page.  It should have an appropriate background picture.
  4. a <nav> subsection under the <div> section that includes references to all four webpages, including this one.
  5. an <article> section that has all of the main components of this page.
  6. a <footer> that has a different background that the <article> section and some closing message.
  7. In the <article> section, you have a set of forms similar to page 3, but with different messages.
  8. In the <article> section, include a video or game.

When you are done with this, compress (Zip) your webpage and your .css file, then turn in the compressed file.

Using the document Variable in JavaScript

JavaScript has multiple "built=in" variables. One of the most widely used is the document variable. You have used it to get an element's ID in a previous example. The document variable has several attributes and methods. One of the attributes is links which is a list of links contained in this document or webpage. Attributes are accessed by a dot extension to the object's name. For example, the links list of the document is accessed by document.links. To get one specific link, just index and use the href attribute of links. For example:

    document.links[o].href // to obtain the URL of the first link.

The lines I added to the code to prink the number of links and the values was as follows: Note, I have put comments on the end of the original two lines between which I added the new code.

       str += " ways to get to school.";           //Original line
       //Beginning of insertion
       numLinks = document.links.length;
       str += "<br>There are " + numLinks.toString()
            + " links in my doucment.";
       if(numLinks > 10) numLinks = 10;
       for (index = 0; index < numLinks; index++)
            str += "<br>Link " + index.toString() + " is "
                 + document.links[index].href;
       // ****** End of insertion
       document.getElementById("storyTime").innerHTML = str;    //Original line

Not All Browsers Handle Scripting the Same Way

The following information is based on the textbook Learning PHP, MySQL & JavaScript by Robin Nixon and is published by O'Reilly in 2015.The JavaScript section starts with Chapter 13 on page 309.


Not all browsers can properly handle <script> sections. Usually, html files can handle the <noscript> tag pair to allow you to at least put out a message if the browser is having trouble with your script. The alternate code could look like:

   If the browser cannot handle your &lt;script> tag pair.
   This could be because the browser has disable JavaScript
   execution or does not support its execution.

The <noscript> goes immediately after your </script> tag. Your script may totally not work on browsers that are too old. Most modern browsers have debugging capabilities. Microsoft has developed a webpage on how to debug JavaScript using Microsoft Edge as the browser and Visual Studio as the debugging platform. Likewise, Google has a similar webpage for debugging JavaScript on a Chrome browser.

Write a MadLib

Using the knowledge you have gained from previous exercises, write a MadLib that tells an interesting story. You may use text boxes, radio buttons, or checkboxes to enter the information for your story. The words you need to have entered include:

  • First Name
  • Last Name
  • Present Tense Verb
  • Color
  • Location
  • Past Tense Verb
  • Activity
  • Day of Week
  • City
  • Adjective
  • Game
  • Adverb - usually ends in ly
  • Present Participle - Verb ending in -ing
  • Outdoor Activity
  • Farewell Greeting

The MadLib Story

Now make a story and substitute in this words. As an example, here is my story:


Fill in the following blanks to tell a story.

Input Column 1 Input Column 2 Input Column 3
First Name:

Last Name:

Present Tense Verb (-s):


Past Tense Verb:


Day of Week:



Adverb (-ly):

Present Participle (-ing):

Outdoor Activity:

Farewell Greeting:

The Story

Just Wait!

Create a Calculator

I asked the class to make a calculator. This is how mine turned out, almost. WordPress messes with the formatting and it does not look as nice in WordPress as it does standalone.



Doing Better in School Takes Grit

Grit, Passion and Perseverance, is emphasized in our school. It is something that we are trying to help the students to learn and adopt as part of their own education. Students can learn it, but it is difficult to teach. In this class, you are required to read the article Grit: The Power of Passion and Perseverance and watch the two included videos. After reading the article and watching the videos, you are to write a summary of what you have learned. Then you are to write a brief description of how you are going to include the following four ideas into your life:

  1. Develop a Fascination
  2. Daily Improvement
  3. Greater Purpose
  4. Growth Mindset

Putting JavaScript in its own file

Steps needed for the first example:

  1. Open your web site project.
  2. Open your last webpage.
  3. In your <head> section, add the following line, changing the name of the file to your
    .js file name: <script type="text/javascript" src="JavaScript.js"></script>
  4. Copy the Mood html code to the bottom of your .html file, change any name/id to have an "e" in front of it.
  5. Create a new file as a JavaScript (.js) file. Make sure the name matches the .js file name you specidied in the <head> of your html file.
  6. Copy the script from the Mood button to the new JavaScript file and change all names to begin with "e". Make sure you do not copy the <script> tags.
  7. Test and see if your are done.