Choose Your Weather
Step outside or look out the window and select your location's weather.
The setWeather Function
The above is a small JavaScript algorithm that replaces the text of a designated paragraph based on what the user selects from a dropdown selection of options — in this case a user's current weather.
The dropdown is created using a select
element which contains a number of options for the user to choose. Each option
is an HTML child of the select
element.
The idea of the algorithm is that when the user chooses an option from the selection, the value assocaited with that option is used as a condition to replace text displayed in the default paragaph below.
If the value of an option is default, another method is invoked to set the selection back to prompt the user to make a selection.
It's important to understand what basic information is needed from the DOM, or the HTML web page, in order to process it for the desired outcome.
The goal is to begin to learn how to break down each step needed in order to build the algorithm, such as:
- a variable for the select element
- a variable for the paragraph element, which will be changed based on user choice
- a function that:
- invokes an onchange method to the select element when the user chooses different options
- assigns the value of the option element to a variable named choice
- utilizes a conditional statement to determine under what circumstances to append the option's associated text to the default paragraph, based on the option the user selects.
To start building the function we'll use the Web API's Document interface which, according to Mozilla's website, serves as an entry point into the web page's content
in order to save the select
and p
elements as variables. This API provides many methods such as getElementByID
When the user makes a selection, a short custom function calls several Javascript Web APIs to display its corresponding text in a paragraph directly below it.
The resetOption Function
The goal of this algorithm is to have the select element's value, the initial one asking the user to make a selection, returned to it's 'default' upon refreshing the screen.
Breaking down this algorithm is as follows:
- define a function, passing in two params: 'selectID' and 'optionToUse'.
- assign the select element's options to a variable, 'selectOptions'
- using a for loop, loop through the indexed options using the assigned variable 'opt', and then increment the loop counter.
- using a conditional operator in an if statement, check to see if the option value equals the parameter passed into the function, e.g., our default option value. If it is, set the select element's index to the matching option from the loop.
- Then break out of the loop.
- Be sure to call the function when it's complete.