Instructor: Cindy Royal
Wed, May 16, 9-11:30am
Description
In this module, you will learn more about programming concepts and apply them in a hands-on exercise.
Outline
I. Overview of HTML/CSS/Bootstrap Concepts
II. Intro to Programming
III. DOM Manipulation
IV. Quiz Exercise
V. Filtering and Visualizing Data
Sample Code for Quiz Exercise
We will be using a variety of HTML form elements to create a quiz that will provide a score to the user. Using the JavaScript Bootstrap Template provided (download and unzip), notice the Bootstrap file structure. Open the index.html file in Brackets (or you can use another html editor). Re-save this file as quiz.html in the same folder, so as to not overwrite the index.html file. Find the content section of the page, an inner div within the #main container. Include the following heading and paragraph to introduce the quiz.
<h1>Test Your Knowledge of JavaScript</h1> <p>Begin the quiz by providing your name.</p>
Forms
We will be creating two forms on the same page. One is a simple form that asks the user’s name. We can use this name in other places in the Quiz to personalize the results. Here is the code for form1. Copy and paste this into your code below the opening heading and paragraph
<form id="form1"> <p><label for="yourname">Name</label> <input type="text" id="yourname" /></p> <button type="submit">Submit</button> </form>
This code has an opening and closing form element, a label and an input of type text. An id of “yourname” has been established to identify the user’s input. I put this in a <p> tag to format it, but you can use any elements or styles to contain these elements. A button with type ‘submit’ is used to Submit the form. Once the value has been captured, it can be used in the page.
DOM Manipulation
The Document Object Model is a representation of the structure and content of the page. To manipulate an element in the DOM, you need a DOM element in which to send the result. Below this form, include this code. This is an empty paragraph with an id of “name”. This will not be visible until the user submits the form. However, if you wanted to start with text in this paragraph, it will be replaced when the form is executed via the script below.
<p id="name"></p>
Script
Below these items, let’s include a script element to include our JavaScript. JavaScript works natively in modern browsers without any additional links or plugins required. Include this code within the script element already provided (don’t repeat the opening and closing script tags).
<script> document.getElementById("form1").onsubmit=function() { yrname = document.getElementById("yourname").value; document.getElementById("name").innerHTML = "Welcome, " + yrname + "!" ; return false; } </script>
The first line provides the code for the event on which the script is executed, in this case the “onsubmit” event. We have created a generic function that gets the value of “yourname”, assigns to a variable named “yrname” and then manipulates the DOM element of “name” with some text concatenated with the “yrname” variable.
The return false; is required to prevent the Submit functions default behavior of refreshing the page. We simply want to manipulate an element on the page. This is not necessary for other types of events.
- Try it and submit the form with your name. If you have problems, use the Chrome Inspector Console to see if it can help you troubleshoot. The Console will often highlight if there is a syntax problem, indicating the row number.
- Change some of the text that is concatenated with the variable in the code and try it again.
Congratulations! You have performed a DOM manipulation.
Show/Hide a Div
Let’s set up a new div for the quiz. By doing so, we can have it hidden, until the user inputs her name.
<div id="quiz"> <p>How well do you know JavaScript? Take this quiz to assess your knowledge of basic programming concepts.</p> </div>
Refresh the page in the browser to see that it is showing.
We will put the rest of the quiz in this element. At the top of the page, find the <style> section. For this element, we want to have it initially hidden with CSS. Include this in the style area.
#quiz { display: none; }
Refresh the page again and that div is now hidden.
Let’s add a line of code to the form1 function to have it appear when that code is executed. Put this above the return false; statement.
document.getElementById("quiz").style.display = "block";
This code changes the display style from none to block, so it is now showing. Refresh the page to be sure it is working.
More Advanced Forms
Let’s create the rest of our quiz. We will use paragraphs for the questions and dropdowns to hold the answers. Review the code below to make sure you understand the html elements. Grab all this code and put in below the opening paragraph in the quiz div.
<form id="form2"> <p>Which of the following concepts represents a portion of a string?</p> <select id="q1"> <option value="0">Choose:</option> <option value="0">concatenation</option> <option value="25">substring</option> <option value="0">variable</option> <option value="0">if statement</option> </select> <p>Which of the following concepts allows you to assign information so it can be used throughout the program?</p> <select id="q2"> <option value="0">Choose:</option> <option value="0">concatenation</option> <option value="25">variable</option> <option value="0">loop</option> <option value="0">iterator</option> </select> <p>Which of the following concepts provides the logic for a choice based on meeting a condition?</p> <select id="q3"> <option value="0">Choose:</option> <option value="0">concatenation</option> <option value="25">if statement</option> <option value="0">loop</option> <option value="0">array</option> </select> <p>Which of the following concepts allows you to store a list of information so it can traversed using a loop?</p> <select id="q4"> <option value="0">Choose:</option> <option value="0">concatenation</option> <option value="25">array</option> <option value="0">variable</option> <option value="0">if statement</option> </select> <br> <button type="submit">Submit</button><button type="reset">Reset</button> </form> <p id="score"></p> <p id="answer"></p>
(Note: radio buttons can also be used to display answers. However, the code for using them is somewhat different, using the querySelector method. See CodeActually Interactive Quiz example for more information).
To make this look a little better, let’s put this in the style section, providing some visual space below each dropdown.
select { margin-bottom: 25px; }
We are giving each answer its own id (q1, q2, q3, q4), so as to assign the value provided to a variable. Notice that each select grouping has values assigned to each option. The correct answer gets 25 points, incorrect gets 0.
There are also two DOM elements after the form is closed. They will be used to hold our results.
Scripting the Quiz
In your scripting area, below where we have been previously working (but above the return false statement;), include this code for form2.
document.getElementById("form2").onsubmit=function() { total = 0; q1 = parseInt(document.getElementById("q1").value); q2 = parseInt(document.getElementById("q2").value); q3 = parseInt(document.getElementById("q3").value); q4 = parseInt(document.getElementById("q4").value); total = q1 + q2 + q3 + q4; document.getElementById("score").innerHTML = "Your score is " + total ; return false; }
In this area, we are initializing a variable name total at 0, so it resets every time the form in submitted. We get the values from each select grouping, but they need to be understood as integers, thus the parseInt statement. A total is calculated. And a score is provided in the total DOM element when the form is submitted.
Refresh the page in the browser. If you have problems, use the Chrome Inspector Console to see if it can help you troubleshoot.
- Can you concatenate the user’s name into the score?
Adding a Response using JSON
JSON or JavaScript Object Notation is a way to store data in a text format on the web. It is an array of objects, holding key/value pairs. You can use a loop to traverse the JSON to filter the data to a specific request. In this case, we are going to use the score and compare it to a value in the JSON to provide a response to the user, as well as a meme. The images are already available in the img folder in the Bootstrap installation.
Grab the following data and include in the form2 function, above the return false; statement.
feedback = [ {total: 0, response: "Did you study", img: "none.jpg"}, {total: 25, response: "Could have done better", img: "poor.jpg"}, {total: 50, response: "Keep trying", img: "below.jpg"}, {total: 75, response: "Almost there", img: "average.jpg"}, {total: 100, response: "You're a JavaScript Expert!", img: "excellent.jpg"}, ]; for(i=0;i<feedback.length; i++) { if(total == feedback[i].total){ document.getElementById("answer").innerHTML = feedback[i].response + "<br><img src=img/" + feedback[i].img + " width=400 />" ; } }
Notice the for loop that uses the iterator “i” to traverse each item in the JSON. Using the if statement, when it finds a match with the value of score, it provides the response. And if you have the images in the img folder, it provides the meme image and establishes a width, concatenating html into the answer.
Refresh the page in the browser. If you have problems, use the Chrome Inspector Console to see if it can help you troubleshoot.
All of these items can be adjusted for your own purposes and layout.
Exercise:
- Make sure you have a working quiz with the code provided above. If you have problems, use the Chrome Inspector Console to see if it can help you troubleshoot.
- Concatenate the user’s name into the responses somehow, as you did with the score.
- Add a question to this quiz. What do you need to change to make it work with 5 questions? Consider the question’s unique id, the point values, the way the value is assigned and added to total, and how the json works to report the result. Create another response and find another image (save it in the image folder) to represent a new score value.
Data Visualization Exercise Using JavaScript and Plotly.js API
Now that you have some basic JavaScript skills, you can use them to create all kinds of interactive Web presentations. One thing you could do is create an interactive chart using a charting package. The Plotly.js API has numerous charts with script that can be manipulated. We may not have time to do this exercise in person, but you can find the instructions here and go through the exercise on your own. You may choose this exercise as part of your curriculum project.