Interactive JavaScript
What is it?
The JavaScript functions that allow you to make interactive web pages.
Why should I learn it?
Your HTML pages need JavaScript to become more interactive.
What can I do with it?
You can change the elements of a page based on a user's input. You will learn about manipulating the Document Object Model (DOM) to customize pages and present data.
How long will it take?
Programming is something that you learn over time, through practice. But in a few hours, you will be introduced to the interactive elements of JavaScript that you will be able to apply to your own projects. Subsequent exercises will more complex applications of interactive JavaScript.
Resources
- Glitch examples for you to Remix
- LinkedIn Learning
- Codecademy
- JavaScript Reference
- Book: JavaScript and JQuery: Interactive Frontend Web Development
Getting Started
Now is a good time to switch over to writing code in an HTML document. In the last lesson, you learned some basic programming concepts. Now we'll work with some practical applications. Open a text editor like Brackets or Atom and use it to write the code, just as we did in the HTML and CSS exercises. Save your files with .html extension (any name is fine, something like javascript.html or do a different file with a new name for each exercise.). Open the html file that includes the JavaScript in the browser.
Like CSS, you can include your JavaScript in a separate file that you link to all your pages. That is recommended if you are using functions that will be repeated on multiple pages. JavaScript files should have a .js extension. This is how you reference the .js file in the HTML document.
JavaScript files are often saved in a separate folder, so make sure your path to the .js file is relative to the file in which you are linking it.
For these exercises, however, we'll be developing the JavaScript within the HTML pages, since it will just be applying to the page in which we are working. You will notice some sections of the code look like regular HTML. When we want to add code, we do that within the script tag.
getElementById(); is a magical method that you can use to access parts of a Web page. We'll be working with this and other functions that "manipulate the DOM" or change the Document Object Model. We'll apply this method to change what is displayed on the page or the "innerHTML" or "value" of the element to which we are applying it. This will be very powerful when combined with forms to ask a user for input to change something on a page.
There are other methods like getElementById, including getElementsbyTagName, getElementsbyClassName and querySelector that you may need to use to achieve certain functionality, but we will start with getElementById, since it is designed to change one element on a page.
Interactivity with a Prompt
Let’s properly structure the document to include the HTML5 doctype declaration.
We'll make a page that prompts for a name and then changes the innerHTML of the document to reflect that name. Copy the code on the right and paste it into a text document.
Notice that the code includes a span with an id of "firstname." A span is like a div, except that it displays inline, where a div creates a new block. We'll be filling that span with the result of the prompt. We open the getElementbyId method with the document object and include the innerHTML property. Then we assign the value "first" that was collected from the prompt.
Code Sample - Basic Interactivity
Interactivity with Multiple Prompts
You can include multiple prompts assigned to different variable names to add more information to the page. For example, you could also prompt for last name, email and other information.
Remember the previous exercise where you determined your popstar name? Let's create a script that prompts for first and last name and calculates it for anyone.
Code Sample - Multiple Prompts
Interactivity with an if Statement
You can now start implementing different techniques to have your programs make decisions. Let's use an if statement to determine if someone's password is of an appropriate length. See the script at the right that prompts for a password, determines the number of characters and provides a response as to whether the password is greater than or equal to 8 characters or not.
Code Sample - if Statement
Do a Calculation
You can use programming to, of course, do some good ole math. The script to the right prompts the user for two numbers, then adds them. Look, a calculator!
Notice in the code the use of the parseInt method. When a variable is created with a prompt, the program doesn't know yet that it is a number. You use parseInt to convert it to a whole number or use parseFloat if you want the numbers to be able to include decimals.
Play around with the code to do some of your own calculations, based on the math operators we learned in the previous exercise.
Code Sample - Calculation
Change the program around to perform some different types of calculations on your own.
Events
You can use events to execute JavaScript commands based on actions on the screen. An event is an interaction – onclick, onload, onmouseover, onmouseout, onsubmit, onchange.
A simple script to illustrate the use of an event is provided to the right. It includes an "onclick" event on the h1 element. The script, which is simply called within the h1 element, uses the "this" object to indicate the current element and changes the innerHTML. Later, we'll use onsubmit and onchange for events based on form actions from a user.
Code Sample - Event
Change the program to use the onmouseover event, instead of onclick. Consider the situations in which one is preferred over the other.
Interactivity with Form
So far, we have received inputs from users via prompts and events. But a more efficient way is to use forms to capture multiple items and execute a script on the onsubmit event.
The code to the right creates a form (remember the code from the HTML Forms tutorial) that asks for a first and last name in two different text fields. When the user submits the form, the document reflects a welcome message that is customized for the user.
Notice that we have an onsubmit event applied to the id associated with the form. Then the script executes a generic function that stores the form inputs in variables and manipulates the DOM element "yourname" to include a welcome message that is customized for the user.
There are other things you can manipulate with getElementById. You can change the style of an element by including a style property.
Add these lines of code above to the end of your script (before return false; to see how styles can be manipulated interactively.
Also notice theCode Sample - Forms
The code above has been modified to use the label element with the form inputs.
Exercise: Add another input item for City to this form and create a DOM element to receive it, then modify the script to manipulate the DOM to include this new information.
Can you use the style property to change the color of the response to orange?
What if you just wanted the city to be orange? Hint: think about how you have the DOM elements set up in the HTML.
Form with Array and for Loop
Let's create a form that asks for three names. We want to use the length method to evaluate the number of characters in each. Instead of doing this three different times, let's create a loop that reads each item from the array that we create to hold the items. We grab the value of each form element. The script then writes a line that includes each name and some text including the number of characters on a separate line. Notice that the loop condition evaluates to namelist.length, which means it is continuing until the end of the array. When the length property is used on an array, it returns the number of elements in the array.
Also notice theUse the code to the right to create your script and run the file.
Code Sample - Forms
Notice in the code above the use of "+=". This appends to the innerHTML rather than overwriting.
Exercise 1: Add a calculation that adds up the characters in the three names. Create another element with an id to hold that answer.
Exercise 2: Modify this code yourself to add an if statement that adds an asterisk if the name has more than four characters. You will probably need an else statement to handle what it should do if it doesn't.
Exercise 3: Modify the code so that the user can input a number of characters to evaluate. Instead of checking for four characters, it will check for the number indicated.
Dropdowns and Radio Buttons
Using Dropdowns
Dropdowns are similar to text inputs. You simply use getElementById to grab the value and put it in a variable. Notice that you can use the onchange event without a submit button, because that event does not cause the browser to refresh the page. That also means you get remove the "return false" statement. You decide which type of event is appropriate for the type of interaction you desire.
Code Sample - Dropdown
Exercise: Add another dropdown to this form and create a DOM element to receive it, then modify the script to manipulate the DOM to include this new information when each dropdown changes.
Using Radio Buttons with querySelector
Radio buttons function a little differently than text inputs or dropdowns, because we are using the code to assess which value is checked. You use the querySelector method to select the checked value in the series with the shared name. We will use this method in the Interactive Quiz tutorial.
Notice that the "for" attribute with the label element allows the user to click the text to also select the radio button. In the example to the right, the label element surrounds each input and it is styled to add a new line. But you should use any styles you need to create the proper layout, including those available for Bootstrap Forms.
Code Sample - querySelector
Exercise: Add another radio button series to this form and create a DOM element to receive it, then modify the script to manipulate the DOM to include this new information when the form is submitted. This can represent different questions.
Another exercise
Use the script to the right to start to provide solutions to the following problems. The form and input element are already set up for someone to submit a password, and there are several DOM elements already set up to hold your answers.
- Return the password to a DOM element.
- Return the number of characters in that word to a DOM element
- Return the first character to a DOM element.
- Return the last character to a DOM element.
- Use an if statement to test if the first character is uppercase and indicate in a DOM element. Hint for 5 & 6: (letter.toUpperCase() == letter) changes the letter to uppercase and checks to see if it is the same as the original letter. If so, then it is uppercase.
- Use a loop to test if any character is uppercase and indicate in a DOM element.
Notice that a generic function is set up using the onsubmit function associated with the form with the "form1" id. Everything you do must go within this function. The return false; statement is required so that the form doesn't submit, only the DOM changes.
You should be able to get 1-3 pretty easily. 4-6 are a little more challenging. Take your time, think through the algorithm. Don't let the code beat you!
Code Sample - Another
Side Note
The document object is part of the Document Object Model (DOM). The DOM is an application programming interface (API) associated with the page that allows you to access and change things with JavaScript, as we did with getElementById(). There are other objects associated with the DOM. Some objects are browser objects (i.e. window). You can get more information on the DOM at CSS Tricks and W3C.
We are starting to add interactivity to Web pages. The Web pages we are working on here simply demonstrate the functionality. Remember that you will need to include this functionality in well designed, responsive websites, as you learned in previous lessons. Think about the layout structure and how you can create a div or series of divs to include your form and resulting functionality.
Moving On
You've had a lot of experience now with using programming techniques to solve a variety of problems. Next we’ll apply more comprehensive techniques in making an Interactive Quiz and with the Interactive Charting Exercise.