Skip to content
  • iImagine
  • Register
  • Log In

Web Development School

Learning made easy.

  • Books
    • Beginning Web Development with ASP.Net Core & Client-Side Technologies
      • TOC
      • Part 1
        • Chapter 1: Static HTML – Designing the landing page
      • Part 2
        • Chapter 2: ASP.Net Core – Let’s talk Dynamic
        • Chapter 3: Introduction to ASP.Net Core MVC
          [ASP.Net Core v9]
      • Part 4
        • Chapter 7: Using Server Side & Client Side technologies together
          [ASP.Net Core v7 & Angular 15]
  • Environment Setup
    • Installing Angular
    • Installing Visual Studio 2022
    • Installing SQL Server 2022 Express
    • Installing Postman
    • Installing Git for Windows
  • Blog
  • iImagine WebSolutions
  • Events
  • Learning Videos
  • Toggle search form

JavaScript Code Improvements

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.

Download

And see it work here.

Table Of Contents
  1. JavaScript Variables
  2. Custom Reusable Functions
  3. Calling JavaScript functions from within other functions
    • Programming structures
      • Conditional Statements
  4. What's Next

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.

Note: JavaScript is a case sensitive language. In the above statement, the getElementById(id) method passes the literal string “cars” as an argument, or parameter. If you passed, “Cars”, or “CARS” the statement would not work. The id of the element you are trying to get must match exactly to what it is defined as on the element itself; In this case, all lower case characters in “cars”:
<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 () */
Note: We refer to functions we write our selves such as showAll(), resetResults(), and showResults(), as custom functions. JavaScript also provides many functions out-of-the-box. For instance, changing a number to a string:
2.toString();
Or, changing a string to a number:
“5”.toNumber();
Changing a data value from one type of data to another like this is called casting.

Calling JavaScript functions from within other functions

The third function is called showResults. This function takes two arguments:

  1. resultsSet: lets the function know what result set to display; ALL, carsResults, jeepResults, or truckResults. If the result set is “ALL”, then the showAll() function is called. Otherwise, we “clear out” the results by calling resetResults which sets all the result set div elements style.display property to none. Finally, we set the style.display property of the resultsSet passed as a parameter to block in order to make those results visible.
  2. 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.

  1. Sequential statements: This programming structure is simply one or many programming commands laid out sequentially in the order you want them to be called.
  2. 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.
  3. 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.
    1. For Loop
    2. For In Loop
    3. For Of Loop
    4. While Loop

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.

< Prev
Next >

Leave a ReplyCancel reply

Chapter 1: Static HTML – Designing the landing page.

  • Static HTML – Designing the landing page.
  • Let’s get started!
  • Mock your site with HTML
  • Make CSS easy with Bootstrap
  • Mock your content
  • Introducing JavaScript
  • JavaScript Code Improvements
  • Results Data
  • Images and the HTML Image Element.
  • Revisiting Reusability for CSS and JavaScript
  • Reuse for HTML: PART 1
  • Reuse for HTML: PART 2
  • Details Page – Using a Bootstrap Component
  • Creating Links
  • Chapter One Conclusion

Chapter 2: ASP.Net Core – Let’s talk Dynamic

  • Introduction to ASP.Net Core
  • What is .Net?
  • What is ASP.Net
  • Introduction to Entity Framework Core

Chapter 3: ASP.Net MVC Core – Models, Views, and Controllers [ASP.Net Core v9]

  • Introduction to ASP.Net Core MVC
  • Create the project: ASP.Net Core MVC
  • Explore the ASP.Net Core Empty Web Project Template
  • Configure the Application for MVC
  • Create a Controller: Home Controller
  • Create a View: Index View for the Home Controller
  • Install Bootstrap using Libman
  • Create the Layout template
  • Create the Model
  • Install EF Core & Create the Database
  • Seed the Database: Loading test data
  • DI (Dependency Injection): Display a List of Vehicles
  • Repository Pattern: The Vehicles Repo
  • Unit Test 1: Home Controller Can Use Vehicle Repository
  • Unit Test 2: Vehicle Repository Can Return List
  • Add the ImagePath Migration and Thumbnail images to results
  • Pagination: Create a Custom Tag Helper
  • Sorting
  • Category Filter
  • Partial View: Break out the vehicle results
  • View Component: Create dynamic category buttons
  • Create the Details page
  • Create the Create Page
  • Create the Update Page

Chapter 7: Using Server Side & Client Side technologies together. [ASP.Net Core v7 & Angular v15]

  • Intro to Full Stack Development
  • Fred’s Cars – Full Stack Development
  • Prepare the environment
  • Create the Visual Studio Solution
  • Add the ASP.Net Core Web API project
  • Add the Angular Project
  • Wire it up!
  • WeatherForecast: Understanding the basics
  • Vehicles API Controller: Mock Data
  • Vehicles Angular Component: Consuming Data
  • Routing and Navigation
  • Using a Component Library: Angular Material
  • Our first Angular Material Component: MatToolbar
  • Configuring for Saas: CSS with superpowers
  • Create the Header & Footer components
  • Displaying Results with MatTable
  • Loading: Using a Progress Spinner
  • MatTable: Client-Side Paging and Sorting
  • MatSidenav: Create a Search Sidebar
  • MatCheckbox: Category Search UI
  • Adding an image to the welcome page
  • Create the database with Entity Framework Core migrations
  • MatPaginator & PageEvent: Custom Server-Side Paging
  • Unit Testing: Custom Server-Side Paging
  • Repository Pattern: VehicleRepository
  • Unit Test: Paging in the Vehicles controller
  • Server-Side Sorting
  • Unit Tests: Sorting
  • Filter (Quick Search)
  • Unit Tests: Filter feature
  • Advanced Search: Categories
  • Unit Tests: Search by category
  • Progress Spinner: Final Fix

TOC

  • What were WebForms?
  • Enter MVC
    • Understanding MVC
    • Advantages of MVC
  • ASP.Net Core MVC – A total rewrite
  • ASP.Net Core 2 MVC – Here come Razor Pages
    • Understanding Razor Pages
  • ASP.Net Core 3 – Dropping the MVC reference
    • Understanding Blazor
  • Dropping the MVC reference
  • Hello .Net 5!
  • What’s Next? – Here comes .Net 6.

Recent Posts

  • Angular Commands Cheat Sheet
  • Installing Git for Windows
  • Installing Postman
  • Installing SQL Server 2022 Express
  • Installing Visual Studio 2022

Recent Comments

No comments to show.

Archives

  • November 2023
  • October 2023
  • June 2023
  • October 2021

Categories

  • Angular
  • ASP.Net
  • Environment Setup
  • See All
  • SQL Server
  • Visual Studio
  • Web API & Rest Services

WordPress Theme Editor

Copyright © 2025 Web Development School.

Powered by PressBook Blog WordPress theme