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

BuzzFeed Style Quiz - New Scoring Algorithm

Copy and paste the code to the right into a text editor and save with an html extension. This script uses a different algorithm for scoring a quiz. It allows you to give points to a specific category, rather than simply tally up a total. Each question gives a point to one of the category answers and then the category with the highest score is the one that is returned with feedback. It uses a variety of advanced techniques to find out which category has the highest score and at which index number it is. Then that index number is matched to the "scores" section to provide the feedback.

The script uses a function to score the quiz that can be called for each question as a parameter. You could also use a second parameter for the value, if you want to score some questions with a number other than 1.

Code Sample - BuzzFeed Stye Quiz - New Scoring

BuzzFeed Quiz with Dropdown

This example is the same as above, except one of the form elements is a dropdown instead of a radio button series. Getting the value from a dropdown is actually easier than getting it for a radio button. You just use the getElementById function to capture the value from the selection.

This script uses the advanced algorithm for scoring from the example above. The same suggestions as above apply to this script: improve the design, add visual interest, weight the calculation differently, add an image for the answer and/or add additional questions.

Code Sample - BuzzFeed Style Quiz with Dropdown

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 age from the Dropdown to the #userage element. Get it work for ages 18-30 first. Then progress to the next item. You will fix those the under and over scenarios in a later item.
  3. Return the number from the radio button series to #taconum.

A Little More Advanced

  1. If the user picks "under 18" or "over 30" have an appropriate message displayed.
  2. Calculate the year that the user was born based on age and return to the #year DOM element. If the user picked "under 18" or "over 30" have it say something like "You were born after ___" or "You were born before ___". Hint: You can probably accomplish this within the if statements from the previous item.
  3. Calculate a subtotal for tacos. Assume tacos cost $2.49 each. Return that to the #tacosubtotal element
  4. Calculate the tax on the tacos. Assume 6.25%. Return that to the #tacotax element
  5. 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(myage == 0) {
//code stuff here
}

else if(myage == 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. 

© 2016 CodeActually · cindy@codeactually.com