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
    1. Redo the Mood code with JavaScript in own File
    2. JavaScript Number guessing Game
  11. Debugging your HTML/CSS/JavaScript Code
  12. Creating a Slide Show
  13. Group Quiz and Review

Introduction

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>

            <script>
                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;
                }
            </script>

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.

0

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">
                <tbody>
                    <tr>
                        <th>Input Form/Name</th>
                        <th>Radio Buttons/Position</th>
                        <th>Check Boxes/Transportation</th>
                        <th>Submittal Button</th>
                    </tr>
                    <tr>
                        <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>
                        </td>
                        <td>
                            <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>
                        </td>
                        <td>
                            <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>
                            </form>
                        </td>
                        <td align="center">
                            <form>
                                <input type="button" onclick="mySubmittal()" name="Submit" value="Submit">
                            </form>
                        </td>
                    </tr>
                </tbody>
            </table>

            <h3>The Story</h3>

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

            <script>
                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;
                            entries++;
                        }
                    }
                    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;
                }
            </script>

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

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

Last Name:

E-Mail Address:
MS Student
High School Student
Teacher
Administrator
Other
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="https://www.youtube.com/embed/arj7oStGLkU" 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.

<noscript>

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:

<noscript>
   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.
</noscript>

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:

MadLib

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):

Color:

Location:
Past Tense Verb:

Activity:

Day of Week:

City:

Adjective:
Game:

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

This section tells you how to write your JavaScript in a separate file and then use your HTML code to use the functions in the "stand-alone" file.

Redo the Mood code with JavaScript in 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.

JavaScript Number guessing Game

Eventually, this should look very similar to your Python program that you wrote earlier in the semester. Like the Python program, this implementation will be done in short sections. The first will deal mostly with your user interface. The hint code will be added later. You will notice that the box containing the generated answer appears on the screen. This is on purpose. It will help you debug your code as you are coordinating your HTML and JavaScript files. In order to have this working, you need to make sure that your external Mood program works.

The HTML interface is as follows:

  <h2><a name="guessNum" id="guessNum"></a>Guess the Number Game</h2>
  <p>
     Number of zeros in maximum number - default 3 (1,000): <input type="text" size="18" id="exponent">
       <button onclick="eStartGame()"><b>Start Game</b></button>
  </p>
  <p>
     Your number has <q id="eGameStarted">not been generated.</q>
        <input type="text" size="18" id="eAnswer">
  </p>
  <p>Choose a number between <q>1</q> and  <q id="eMaxNum">1000</q></p>
  <p>Enter your guess: <input type="text" size="18" id="eGuess"> 
                       <button onclick="eCheckGuess()"><b>Check Your Guess</b></button></p>
  <p>You have made <q id="eCount">0</q> guesses and your answer is <q id="eResults">not made</q>.</p>

while the JavaScript (.js) code is as follows:

// Start of the number guessing game.
// First the number generator
function eStartGame() {
    document.getElementById("eGameStarted").innerHTML = "been generated";
    var expnnt = document.getElementById("exponent").value;
    if (expnnt <= 0) expnnt = 3;
    document.getElementById("eAnswer").value = expnnt;
    var maxNum = Math.pow(10, expnnt);
    document.getElementById("eMaxNum").innerHTML = maxNum;
    document.getElementById("eAnswer").value = Math.floor((Math.random() * maxNum) + 1);
    return;
}

// Now check for guess matching the answer
function eCheckGuess() {
    var guess = document.getElementById("eGuess").value;
    var answer = document.getElementById("eAnswer").value;
    var count = parseInt(document.getElementById("eCount").innerHTML,10);
    count += 1;
    document.getElementById("eCount").innerHTML = count;
    var results = "not correct";
    if (guess == answer) {
        results = "correct";
    }
    document.getElementById("eResults").innerHTML = results;
}

The first assignment is to get this up and working. Then finish the logic to make it fun. Turn in the finished assignment to Completed Number Guessing Game. The instructions on this assignment page are:

Take the code on my webpage and insert it into the proper files. Then complete the JavaScript so that the guessing game is useful and fun. I have been looking at some JavaScript fireworks code to celebrate a victory. One such page is https://airbrake.io/blog/javascript/fourth-of-july-javascript-fireworks. Take a look at it and see what you would like to do. Another example is floating balloons: http://rainbow.arch.scriptmania.com/scripts/bg/float_up.html Neither is required, but they may be nice for celebrating a victory.

Debugging your HTML/CSS/JavaScript Code

Debugging your HTML/CSS/JavaScript code is easier with Visual Studios. Once you have edited all three files, point to your *.html that you want to check. Visual Studios will go through your Style Sheet and JavaScript files as well as your HTML file to discover any recognized problems. VS will analyze the files and create Warnings for each of these files. Usually Warnings indicate something that will cause problems but will not necessarily prevent your webpage from displaying. The one exception is your JavaScript code. It will point out problems it recognizes, but it does not yet have the capability of pointing out problems with your JavaScript file that would prevent the execution of your code. I am currently working on figuring out how to use Visual Studios to actually debug JavaScript code.

Creating a Slide Show

Making a slide show first requires buttons and a way to count up and down. The following section of code does that for you. The next section adds the actual slides and captions. The buttons I use are my calculator functions defined in my CSS file:

.calculator {
    width: 55px;
    height: 45px;
    font-size: 32px;
    cursor: pointer;
    text-align: center;
    text-decoration: none;
    outline: none;
    color: darkgreen;
    background-color: lightgreen;
    border: ridge;
    border-radius: 50%;
    box-shadow: 0 12px gray;
}

.calculator:hover {
    background-color: lightgray;
}

.calculator:active {
    background-color: darkgreen;
    color: lightgreen;
    box-shadow: 0 5px #666;
    transform: translateY(4px);
}

.calculator.orange {
    color: black;
    background-color: #FF9933;
    border-bottom: black 2px solid;
    border-top: 2px #FF9933 solid;
}

.calculator.blue {
    color: darkblue;
    background-color: lightseagreen;
    border-bottom: black 2px solid;
    border-top: 2px lightseagreen solid;
}

When the time comes, choose between the orange and blue buttons, you do not need both. The HTML code is:

            <h2></a>Creating a Slide Show</h2>

            We are on slide <q id="eItem">1</q> of <q id="eLength">to be calulated</q><br /><br />
            <button class="calculator blue" onclick='changeSlide("L")'><b>&#8678;</b></button>
            <button class="calculator blue" onclick='changeSlide("R")'>&#8680;</b></button>
            <button class="calculator orange" onclick='changeSlide("L")'>&#8678;</b></button>
            <button class="calculator orange" onclick='changeSlide("R")'><b>&#8680;</b></button>
            <br /><br />

and JavaScript is:

// Go up and down through the potential slides.
function changeSlide(val) {
    var len = 7;
    document.getElementById("eLength").innerHTML = len;
    index = document.getElementById("eItem").innerHTML - 1;
    if (val === "R") {
        index++;
        if (index >= len) index = 0;
    }
    else {
         index--;
        if (index < 0) index = len-1;
    }
    document.getElementById("eItem").innerHTML = index + 1;
}

Group Quiz and Review

We have been working on HTML, CSS, and JavaScript for awhile. A review would be good at this time. The questions are:

  1. What have you learned that is of the most useful to you?
  2. What is the meaning of HTML and how is it used?
  3. What is the meaning of CSS and how is it used?
  4. How have you used JavaScript?
  5. How are you going to use the Python and Web development tools you have learned in this class?