By the end of the last module we had our webpage to the point where we have some JavaScript interaction with the user and enabled them to select which category of vehicles they would like to view.
In this section we will make some improvements to the current JavaScript code to make it a bit more concise.
You can download the completed version of fredscars.html for this module with the completed HTML here.
And see it work here.
JavaScript Variables
In our current code we are using the following statement twenty times:
document.getElementById(id)...
This is a bit repetitive and can get kind of hard to read. This statement accesses an element object from the DOM Tree stored in computer memory and we are simply using properties of that object, such as onclick, style, and innerHTML.
The first improvement we are going to make is to change our document.getElementById(id) statements to variables.
w3Schools defines variables as “containers” for storing data (values). Variables are also stored in computer memory and are used to hold single data values or point to other objects in memory such as our DOM Elements.
We are going to explicitly define our variables and make the code a bit more readable.
Modify the contents of fredscars.html with the following code, save your file, and refresh your browser:
C:\Development\FredsCars\HTML\Chapter01Mod7\FredsCars.html
<!-- ... -->
<script>
window.onload = function () {
// button variables
var btnAll = document.getElementById("btnAll");
var btnCars = document.getElementById("btnCars");
var btnTrucks = document.getElementById("btnTrucks");
var btnJeeps = document.getElementById("btnJeeps");
// result variables
var carResults = document.getElementById("cars");
var truckResults = document.getElementById("trucks");
var jeepResults = document.getElementById("jeeps");
var resultsHeader = document.getElementById("resultsType");
// all
btnAll.onclick = function () {
carResults.style.display = "block";
truckResults.style.display = "block";
jeepResults.style.display = "block";
resultsHeader.innerHTML = "ALL";
}
// cars
btnCars.onclick = function () {
carResults.style.display = "block";
truckResults.style.display = "none";
jeepResults.style.display = "none";
resultsHeader.innerHTML = "CARS";
}
// trucks
btnTrucks.onclick = function () {
carResults.style.display = "none";
truckResults.style.display = "block";
jeepResults.style.display = "none";
resultsHeader.innerHTML = "TRUCKS";
}
// jeeps
btnJeeps.onclick = function () {
carResults.style.display = "none";
truckResults.style.display = "none";
jeepResults.style.display = "block";
resultsHeader.innerHTML = "JEEPS";
}
};
</script>
<!-- ... -->
At this point when you refresh your browser there will be no functional or appearance changes. But the JavaScript code is becoming much more readable.
At the top of the code we have defined four button variables and four result variables.
Our button variables look like this using cars as an example:
// button variable
var btnCars = document.getElementById("btnCars");
Above we declare a variable with “var btnCars
” and assign to that variable the results of the document.getElementById("btnCars")
method. Our btnCars variable now points to the btnCars <div> element:
<div id="btnCars" class="buttonContainer"><button class="btn btn-primary button"><b>CARS</b></button></div>
Then we can assign a function to the same onclick property we had before but this time using the new explicit button variable:
Car Button Function
// cars
btnCars.onclick = function () {
carResults.style.display = "block";
truckResults.style.display = "none";
jeepResults.style.display = "none";
resultsHeader.innerHTML = "CARS";
}
The result variables work the same way:
// result variables
var carResults = document.getElementById("cars");
And the new carResults variable is accessed from the Car Button Function code above where we set it’s display attribute to block just as before.
<div id="cars" style="display: block;">
<h3>CARS</h3>
</div>
Custom Reusable Functions
The code is starting to look much nicer already. We are now accessing properties and methods of objects represented by variables with self describing names. But it can still be improved. We are basically repeating the same code for all four button clicks.
There is a software engineering principle called DRY (DO NOT REPEAT YOURSELF). We’ll explore this concept more in later chapters but for now when you see yourself repeating code like this it’s good practice to make a reusable version of the code so that it is defined once and called from the same spot every time.
Modify the contents of fredscars.html with the following code, save your file, and refresh your browser:
<!-- ... -->
<script>
window.onload = function () {
// button variables
var btnAll = document.getElementById("btnAll");
var btnCars = document.getElementById("btnCars");
var btnTrucks = document.getElementById("btnTrucks");
var btnJeeps = document.getElementById("btnJeeps");
// result variables
var carResults = document.getElementById("cars");
var truckResults = document.getElementById("trucks");
var jeepResults = document.getElementById("jeeps");
var resultsHeader = document.getElementById("resultsType");
// all
btnAll.onclick = function () {
showResults("ALL", "ALL")
}
// cars
btnCars.onclick = function () {
showResults(carResults, "CARS");
}
// trucks
btnTrucks.onclick = function () {
showResults(truckResults, "TRUCKS");
}
// jeeps
btnJeeps.onclick = function () {
showResults(jeepResults, "JEEPS");
}
function showAll(){
carResults.style.display = "block";
truckResults.style.display = "block";
jeepResults.style.display = "block";
}
function resetResults(){
carResults.style.display = "none";
truckResults.style.display = "none";
jeepResults.style.display = "none";
}
function showResults(resultsSet, resultsText){
if (resultsSet == "ALL"){
showAll()
} else {
resetResults();
resultsSet.style.display = "block";
}
resultsHeader.innerHTML = resultsText;
}
};
</script>
<!-- ... -->
In the above code we have defined three new functions.
The first function is called showAll
. This function sets all three result areas’ style.display
attribute to block
making them all visible.
The second function, resetResults
, sets all three result areas’ style.display
attribute to none
making them all invisible.
These first two functions are called parameterless functions because they do not take any arguments or parameters in the paranthesis portion of the function definition at the end:
function showAll() /* empty argument list between parenthesis () */
function resetResults() /* empty argument list between parenthesis () */
Calling JavaScript functions from within other functions
The third function is called showResults
. This function takes two arguments:
resultsSet
: lets the function know what result set to display; ALL, carsResults, jeepResults, or truckResults. If the result set is “ALL”, then theshowAll()
function is called. Otherwise, we “clear out” the results by callingresetResults
which sets all the result set div elementsstyle.display
property tonone
. Finally, we set thestyle.display
property of the resultsSet passed as a parameter toblock
in order to make those results visible.resultsText
: lets the function know what text should be displayed in the results header.
function showResults(resultsSet, resultsText) /* two arguments defined between parenthesis */
Our button variables, using cars again as an example, each call our new custom function, showResults
:
// cars
btnCars.onclick = function () {
showResults(carsResults, "CARS");
}
In our car button onclick
function above, we are passing our explicit carsResults
variable defined at the top of our code file as the first argument to the showResults
function directing it to show the cars result set <div> element. We also pass the literal text string “CARS” as the second argument directing showResults() to display “CARS” as the text in the results header.

Programming structures
Scripting and Programming languages like JavaScript and C# have three types of programming structures.
Sequential statements
: This programming structure is simply one or many programming commands laid out sequentially in the order you want them to be called.Conditional statements
: Conditional Statements let you make decisions in your code about whether to execute one set of statements or an alternative set of statements depending on a condition such as what value was passed in for an argument.Looping statements
: Looping constructs let you execute a group of statments over and over again until a certain condition is met. There are several types of Looping statements and we will see examples in following chapters. For now here is some documentation on JavaScript looping you can read at w3schools if you want to explore further yourself.
In the showResults
function we are using a type of conditional statement called an if then else statement.
function showResults(resultsSet, resultsText){
if (resultsSet == "ALL"){
showAll()
} else {
resetResults();
resultsSet.style.display = "block";
}
}
Conditional Statements
Let’s look at the code above in our showResults
function.
If the resultsSet parameter’s value is equal to “ALL” then we call our new showAll
function and show the user all three result sets.
If the resultsSet parameter’s value is equal to anything else other then “ALL”, we call our new resetResults
function setting all result areas to a display value of none
making them all invisible. Lastly we use one of our new result variables passed to us using the function’s resultsSet argument and from there set the display value of the correct resultSet to block
making the user’s choice of results visible.
In addition to the if/else statement
if (condition) {statements} else {statements}
where you have only two pathways to choose from to execute, there are also other conditional constructs that allow one, two, or multiple groups of code to execute.
One is called the if/else if/else statement and you can have as many else if
statements as you need. The last default condition is just else:
if (condition 1) {
statements
} else if (condition 2) {
statements
} else if (condition 3) {
statements
} else {
statements
}
Another is called a switch statement and looks like the following:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
We have done quite a bit of work in this module. We haven’t made any changes to appearance or functionality but we have cleaned up the code significantly.
We are no longer calling the same statements over and over again in each button click function and have condensed each button click from four statements down to one statements. We were able to do this by taking our repetitive code and separating it out to small reusable sections of code.
What’s Next
Right now when the user clicks a button, we are only showing the header and a placeholder for what results should be displayed such as CARS, TRUCKS, JEEPS or ALL. In the next section we will return to a topic briefly mentioned earlier in the chapter called “Preview to Defining Objects” and start laying out what the results should actually look like when the user clicks a category button.