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.
Resources
- Glitch Examples for you to Remix
- Lynda.com
- Codecademy
- JavaScript Reference
- Book: JavaScript and JQuery: Interactive Frontend Web Development
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.
Making an Interactive App
The code sample provides an example of how you can use JavaScript to create something interactive for your users. This example is a budget calculator. It takes inputs from users for monthly income and several budget items, adds them up, subtracts from income and provides an output of monthly savings. It allows the user to adjust these entries to see where they can improve financial management. In the script, we use the parseInt method to identify the values as integers (but you can also use parseFloat for decimals). You may need to use other methods to format your output properly.
Think about what else you could do with this. What if you wanted to calculate the percentage of revenue for each item and include it next to the expense in form? Hint: In the form, create a span after each label with a unique id
Then do the percentage calculations for each item in the script and return to those ids. For example, the code below divides the individual expense by income and converts to a percentage by multiplying by 100 and concatenating the percent sign as a string. Do this for each expense item.
In this example, styles are used to provide simple formatting for labels and inputs, but you can do whatever you want with styles to create your desired layout. Take your time and consider how you want this to look. This is simple code that provides functionality. Think about how to include this code in an appropriate interface design.
In the Google Charts module, you can see how to apply a chart to demonstrate the expense items.
The potential for creating interactive applications for users is infinite. You just have to determine algorithms and functionality. The functionality of this app is demonstrated below.
Budget Calculator
Code Sample - Budget App
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
The script to the right provides an example for using a dropdown to lookup a value in the JSON section. This is based on Becky Larson's Loud Austin project. In the dropdown, the user selects a zipcode. The script returns the element from the JSON with the key "noise." Becky's project was a lot more complex than this, using the Google Maps API to plot the addresses of the noise complaints from City of Austin data. But you can start to see how you could reference data in a JSON section and replace it in the DOM, based on a user's selection.
This example also introduces some error correction. It first checks to see if the value from the dropdown is greater than 0. If it isn't, then it jumps to the area where it asks the user to make a selection. If it is, then the rest of the script executes. It goes through a loop to make the selection with something in the JSON. When it finds a match, it returns the zipcode itself into the "zip" id and returns the "noise" id the value for noise.
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 a json array of data with values for related artist and Spotify popularity.
I used the Spotify API Console to generate this data for each musician.
You get the musicians URI Code by searching for an Artist on Spotify, finding the three dots next to their name. Under Share, you will find Copy Spotify URI (this is somewhat hidden now, but if you hold the option key while hovering over Share, it will change to Copy Spotify URI). You only need to include the artists's number in the id field, so remove "spotify:artist:" (i.e. 27AzFtMZhRN78bAMPntbpF). You will need to get an APIKey to generate Related Artists, but then the console will generate the json for you. You can get a Spotify API Key by signing up for Spotify (you can use a free version, if you aren't already signed up). I used the JSON to CSV converter, so I could open the data in a spreadsheet and clean up the json to only include a few of the endpoints I might want to work with. Then I added a column to identify the main artist to which each was "related," in this case Old 97s, Spoon and Bob Schneider. I used the CSV to JSON Converter to convert the data back to JSON for the script. Then I referenced the data json array in my script, which pulls data for the main musician selected in the dropdown.
The second set of code samples shows what to change to display the artist and popularity in a table.
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. The script needs a reference to a .json file that holds the data arry of objects in a script tag toward the top of the html in the head section. See the Filtering Large Datasets tutorial for more information on this technique.
Code Sample - Another Dropdown with JSON
To show the results in an organized table, make the following changes to the code sample to reflect table html. Notice how the html is concatenated with the variable names in the script.
In the html area, where the DOM element is located:
In the script, where the innerHTML is changed:
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
Creating an Interactive Info Box
Now that you have explored different ways to use JavaScript to achieve interactivity, it is time to be creative with how you apply interactive elements to your site. The scripts provided show three different ways that you can create an interactive info box. Try the scripts on their own, but then you can move the html into your page in a desired place (like a Bootstrap column) for your layout and move the script into the script area of your site, to achieve the functionality. For each of these examples, if you modify the content in the JSON array, you can apply your own. And you can change or add items, making sure you understand how the dropdowns or buttons access your data. Give each a try!
Interactive Info Box Using a Dropdown
This example uses what you already know in JavaScript by using a dropdown to make a selection, having it match something in a json array and present it on the page. See the example below. But be creative in how you use what you have learned to apply your own interactivity to your site.
Code Sample - Interactive Info Box with Dropdown
Interactive Info Box Using Buttons
This example uses buttons that the user selects to change the view. Basic flexbox CSS is used to make the two columns, but HTML code can be pasted into a Bootstrap column or other layout method to achieve your layout. In the script, this option creates a sendResult function that passes the section name each time a button is submitted.
Code Sample - Interactive Info Box with Buttons
Interactive Info Box with Next Button
The Next Button method works similarly to the Button method above, except there is only one button. Each time the user clicks the button, another button is displayed that executes the code, using the display: block and display: none styles.
Code Sample - Interactive Info Box with Next Button
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
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 in the html. 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 in the form html. In this instance, the "return false" is necessary in the html where the function is called. Either works! Try them both.
Code Sample - Generic Function
Code Sample - Defining a Function
Other Ways to Iterate Over an Array
forEach
Another way to iterate over an array is to use the forEach syntax. forEach takes a function and performs the specified function for each element of the array. It can provide the element (indicated by the first parameter of the function) as well as an optional "index". This can be used with regular function or arrow syntax.
for ... of & for ... in
One final way to iterate over an array is to use the for ... of syntax. This syntax is similar to the ways that other languages, like Python, execute for loops. The loop iterates over each item in the array based on establishing the item with the array in the for declaration.
There is also for ... in syntax, which provides the index number, which can be used to identify the item. For ... in syntax is primarily used to iterate over objects.
These examples simply return the result to a DOM element, but can be used with more complex logic and DOM manipulation techniques. We will continue to use regular for loop syntax for our examples, because it is important to understand the innerworkings of loops. But it is good to be aware of other methods you may encounter or that may simplifly your code.
Code Sample - forEach
Code Sample - for ... of & for... in
Working with Arrays
There are some additional functions in JavaScript that allow you to more simply work with arrays than always having to implement a loop. The .map(), .filter(), .find(), .findIndex(), .every(), .some() and spread features in the code sample shows examples of each.
Each example uses the template string syntax with "backticks" to concatenate variables in strings and the arrow syntax for functions. You can also use regular concatenation and function syntax with these features. Use these methods as necessary when working with data in your projects.
Code Sample - Working with Arrays
Exercise: Write a script that takes the below array, multiplies each element by 3 and finds the index of the first item greater than 100. Hint: create separate functions for the .map() and .findIndex() features with with the proper logic and apply the findIndex function to the new array created by the .map function. It would be helpful to get the .map() feature working first, then apply the .findIndex() feature.
array = [2, 7, 9, 20, 29, 30, 35, 72, 101];
Now try working with these features with strings as items. See the array below. Use the .filter() feature to create a new array with only the items that have four or more characters. Then find the value of the first one that starts with a "p". Also find the index of it in the new array. Return the array, value and index to the DOM in separate statements. Hint: use item.charAt(0) == "p" in your function to find the first character in a string. charAt() let's you find the value of any character in string, starting with 0.
array = ["dog", "cat", "bird", "penguin", "parrot"];
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-7 and try to get as many as possible.
- Return the user's first and last names to the DOM in the #greeting element.
- Return the user's zipcode from the Dropdown to the #zipcode element.
- Return the number from the radio button series to #taconum.
A Little More Advanced
- If the user picks 0 or Other for zipcode, create an appropriate message for "pick a zipcode" or "out of area".
- Calculate a subtotal for tacos. Assume tacos cost $2.49 each. Return that to the #tacosubtotal element
- Calculate the tax on the tacos. Assume 6.25%. Return that to the #tacotax element
- 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.