More Interactive Examples

What is it?

Here are some more scripts that you can use, modify and customize, as you start to consider doing other projects. Feel free to get inspiration from these examples, but make sure to put your own mark on them with design and integrating functionality.

Why should I learn it?

These are just some additional examples. Sometimes you just want to find something that's close, to see how someone else coded it. Get inspiration from these examples.

What can I do with it?

Feel free to modify and customize any of these scripts for your own purposes.

How long will it take?

Take your time with your own projects. You are just getting started. But you know all the basic functionality to solve any problem, with patience and the right mindset.

Getting Started

This isn't an exercise as much as it is a series of completed examples. I don't have step-by-step videos or instructions for these, but you should now be able to make changes to code for your own purposes. Put the code for each in an html file and open in a browser to see them in action.

BuzzFeed Style Quiz

Copy and paste the code to the right into a text editor and save with an html extension. This is a short quiz with three questions. Instead of having a right or wrong answer, it uses values to evaluate something about the user. Depending on the person's score, they get paired up with an Austin-based band.

Use the script for functionality, but you will want to create a more interesting design. For instance, you might include a graphic or photo in the header section for visual interest. You might also want to change the way that the answer is calculated, using different ways to weight the answers. And, you could add an image to correspond to the answer, as we did in the Interactive Quiz tutorial. And you should have more than three questions.

Code Sample - BuzzFeed Stye Quiz

Validating If Elements Are Selected

So far, our forms have required the user to fill out all elements before submitting. If someone forgets to select a radio button or fill out a text field, the form doesn't work. But that's not how forms work in the real world. People make mistakes all the time and your script must anticipate and handle certain mistakes. This can get very complicated, when you consider things like format of entries, but we can start by checking to see if all fields are filled out. If not, we can send the user an alert. See the script to the right and replace the script area in the previous example. The script uses an if statement to check if all elements have a checked value. If so, it progresses with the rest of the script. If not, it moves to the else statement that provides the alert.

This is just one way to handle this situation. You may want to allow people to skip an item. If you want to assign a "default value" for a field if a user doesn't select one, you can use an if statement to check for the value and then the else statement to assign the default value. Try doing this with a series of if/else statements, one for each form element. Be careful that this doesn't skew the results of your quiz or calculator.

Code Sample - Validating If Elements Are Selected

BuzzFeed Style Quiz - More Advanced Algorithm

Sometimes you need to use a more elaborate scoring algorithm. You might want to weight items differently by multiplying them to something before you add them to the result. Or you might want to get a point (or more) each time someone picks an element that meets the criteria for one of your answers - putting each score in a bucket and using the script to evaluate the one with the highest number. The script to the right does that.

Carefully consider your algorithm when you are creating forms with results.

Code Sample - BuzzFeed Stye Quiz

Using Images for Radio Buttons

The code to the right provides an example of using images instead of radio buttons. The key is in connecting the label to the input by using the same identifier for the "for" and "id" attributes respectively for each radio button. Download the files here to use them in your script. See the example below.

Code Sample - Using Images in a Radio Series

Dropdown with JSON

Another Dropdown with JSON

This example uses data that I pulled from the Spotify API. I wanted to get the Related Artists for several musicians. I created three different JSON arrays, one for each band. It also includes the Spotify popularity number. Ideally, these numbers would be formatted better, perhaps using a table.

Code Sample - Another Dropdown with JSON

Dropdown with External JSON script

Sometimes you want to put your script in an external file. Maybe it is being updated by someone else, or you just want to keep the data separate from the rest of your code. You can do this by putting your JSON data in its own file. In this case, I created data.json (see the 2nd code block to the right). All stray characters, quotes and apostrophes in the data must be escaped or removed or else the file won't work.

The script uses the reference to the data.json file in a script tag toward the top of the html in the head section. Play with your own data in this example.

Code Sample - Dropdown with External JSON

Sample Code - data.json

Checkbox and Multiple Selection Dropdown

If you use a checkbox or multiple selection dropdown, you will access the values via an array using the querySelectorAll method. To put these values in an array and then print them out, you can use the following scripts on the right to access the values in the array.

Code Sample - Checkbox

Code Sample - Checkbox Advanced

Code Sample - Multiple Selection Dropdown

Date and Math Calculation

This is a fun little program. This script uses a combination of the date function in javascript and some math to calculate the number of days until SXSW. You can use math to create any number of different types of calculators - financial, grade point average, etc.

Code Sample - Date and Math Calculation

Simple Chart

Another fun little app. This is a scaled down version of the interactive charting example. The user puts in the number of hours for each activity and the script creates a little chart using divs to represent bars.

Code Sample - Daily Activities

Show/Hide Functions

This is a simple example of how to use show/hide functions. You set elements in divs using display: none as the initial style. Then the script reveals them depending on what is chosen in the dropdown. You need to have the images in a folder that the script can access. You can find the images used in this example here. The off() function just makes sure that anything that was turned on gets turned off for the next selection.

Code Sample - Show/Hide

Using Functions to Submit the Form

So far, we have used a "generic" function to submit the form. We identified the form with getElementById, and then included the script to be executed on the onsubmit event within that function. However, you can define a function to be called when you submit a form. You might want to use this function multiple times on a page or throughout a site, so you can call the function when you want to use it. However, for the simple scripts we have done so far, the "generic" function works fine.

Compare the two code samples at the right. The first one is a simple example that we have used with the "generic" function. The second example defines a function named "welcome" and then calls it with the onsubmit event. Either works! Try them both.

Code Sample - Generic Function

Code Sample - Defining a Function

Yet Another Exercise

Here's another exercise to give you experience with DOM manipulation using text, dropdowns and radio buttons. Remember that text and dropdowns use document.getElementById("idname").value syntax and radio buttons use document.querySelector('input[name = "radioname"]:checked').value to capture the value from the form (where "idname" and "radioname" are the names you provide in the form for those elements). Refer to any of our previous exercises for examples.

Start with the code on the right. The form is already set up for you. You should be able to get the first three easily. The last three require some calculation and logic, but you have been exposed to all of them. Use parseInt() if a number needs to be an integer or parseFloat() if you need decimal places. You can fix the number of places on a value with this syntax variable.toFixed(2) where variable is the name of your variable.

You should be able to get all of these. Don't quit until you are able to answer 1-3. Then move on to 4-6 and try to get as many as possible.

  1. Return the user's first and last names to the DOM in the #greeting element.
  2. Return the user's zipcode from the Dropdown to the #zipcode element.
  3. Return the number from the radio button series to #taconum.

A Little More Advanced

  1. If the user picks 0 or Other for zipcode, create an appropriate message for "pick a zipcode" or "out of area".
  2. Calculate a subtotal for tacos. Assume tacos cost $2.49 each. Return that to the #tacosubtotal element
  3. Calculate the tax on the tacos. Assume 6.25%. Return that to the #tacotax element
  4. Calculate the total (subtotal + tax) for tacos and return it to the #tacototal element

Take your time and think through each step, checking in the browser before you do the next step. Use the Chrome Inspector and check the console for any errors as you test. If there are no errors in the inspector, check for spelling or other syntax problems. The web is a good place to look for other examples of correct syntax. Be resourceful. Don't let the code beat you!!!

One more hint: Sometimes you have several items in an if statement that will lead to an else statement for all other conditions. For additional "ifs" use "else if" as follows:

if(myzip == 0) {
//code stuff here

else if(myzip == 999) {
//code stuff here

else {
//code stuff here

Code Sample - Yet Another Exercise

Moving On

All these exercises demonstrate practical use of the features we have discussed. Try them out and customize for your own projects! Next, we'll look at some examples incorporating the Google Maps API. 

© 2017 CodeActually ·