Blog
How to Create a Simple Covid-19 Stats App or Web Page in HTML5, and JavaScript

How to Create a Simple Covid-19 Stats App or Web Page in HTML5, and JavaScript

 154 total views,  1 views today

Advertisements


Coronavirus HTML5 widget and App

Advertisements


  1. Firstly, create a folder with the name “Covid-19”
  2. Create a dummy HTML file with the name “index.html”
  3. Create a folder with the name “assets” inside the project directory.
  4. Create a JavaScript file inside “assets” folder with the name “covidStats.js”.
  5. Let’s start developing the actual HTML5 covid-19 app or covid19 widget.

Add starter boilerplate for Coronavirus HTML5 widget and App like this:

<!DOCTYPE html>
<html>
    <head>
        <title> Covid Stats </title>
    </head>
    <body>
       
    </body>
</html>

Add drop-down list

Add drop-down list and some span elements inside body start and end tags.

Add IDs for the Coronavirus HTML5 widget and App

Also, add some ids “covidCountries”, “countryRegion”, “confirmed”, “recovered”, “deaths”, “active” with the select and span elements which we will use for appending Covid19 API data.

<!DOCTYPE html>
<html>
    <head>
        <title> Covid Stats</title>
    </head>
    <body>
        <!-- Drop down for all countries -->
        <select id="covidCountries">
            <option value="select">Select</option>
        </select>
        <!-- spans for covid stats -->
        <span id="countryRegion"></span><br>
        <span id="confirmed"></span><br>
        <span id="recovered"></span><br>
        <span id="deaths"></span><br>
        <span id="active"></span><br>
    </body>
    
</html>

Add Script

Now, add a script line <script src=”assets/js/covidStats.js”></script> before the </body> tag. This script is the actual script that will use for fetching data from Covid-19 API and for appending that response in the select drop-down and span elements.

Advertisements


<!DOCTYPE html>
<html>
    <head>
        <title> Covid Stats</title>
    </head>
    <body>
        <!-- Drop down for all countries -->
        <select id="covidCountries">
            <option value="select">Select</option>
        </select>
        <!-- spans for covid stats -->
        <span id="countryRegion"></span><br>
        <span id="confirmed"></span><br>
        <span id="recovered"></span><br>
        <span id="deaths"></span><br>
        <span id="active"></span><br>
    </body>
    <script src="assets/js/covidStats.js"></script>
</html>

Write Script

Let’s write the actual script inside the “covidStats.js” file for fetching Covid-19 data.

I am pretty sure, you have already created the “covidStats.js” file inside the assets folder. If not then create this file.

Global Variables

Let’s declare a variable “let covid_stats_global” and initialize it with “null” and an empty array “unique_result_for_countries”.

// let covid stats
let covid_stats_global = null;
let unique_result_for_countries = [];

Window.onload

Add window.onload function.

// load json on window load
window.onload = () => {
  
};

Create an HTTP request inside the window.onload function like this:

let xhttp = new XMLHttpRequest();

First Step: Call actual Covid19 Api or open a request for fetching Covid19 results:

xhttp.open("GET", "https://covid19.mathdro.id/api/confirmed", false);

Second Step: Send the request to the Covid19 API:

xhttp.send();

Third Step: Initialize “covid_stats_global” variable and save JSON in pretty form or converting JSON into an object:

covid_stats_global = JSON.parse(xhttp.responseText);

Fourth Step: Call the “appendCountries” function don’t worry we will define this function after exiting from the current function.

// append countries to country drop down
  appendCountries();

Fifth Step: Invoke switchCovidStats() and pass a parameter “document.getElementById(“covidCountries”).value”.

//   swtiching stats
  switchCovidStats(document.getElementById("covidCountries").value);

Don’t worry we will define these functions later.

window.onload function code

// load json on window load
window.onload = () => {
  // create http request
  let xhttp = new XMLHttpRequest();
  // open request
  xhttp.open("GET", "https://covid19.mathdro.id/api/confirmed", false);
  // send
  xhttp.send();
  // save json in pretty form or converting JSON into object
  covid_stats_global = JSON.parse(xhttp.responseText);
  // test using console
  console.log(covid_stats_global);
  // append countries to country drop down
  appendCountries();
  //   swtiching stats
  switchCovidStats(document.getElementById("covidCountries").value);
};

Let’s create an arrow function “appendCountries”

appendCountries = () => {};

Now follow these steps for writing code inside appendCountries() function:

First Step: Get a country value from the countries select a drop-down element using “covidCountries” id.

// get select element using id
  let countries_drop_down = document.getElementById("covidCountries");

Second Step: Declare a variable “drop_down_items” and initialize it with empty value “”.

let drop_down_items = "";

Third Step: Create an object “lookup_for_duplicate_countries”

// lookup object for duplicate countries
  let lookup_for_duplicate_countries = {};

Fourth Step: Loop through “covid_stats_global”

// for loop for pushing unique countries
  for (covid_state in covid_stats_global) {
    let country_name = covid_stats_global[covid_state].countryRegion;

    if (!(country_name in lookup_for_duplicate_countries)) {
      lookup_for_duplicate_countries[country_name] = 1;
      unique_result_for_countries.push(country_name);
      // console.log(country_name);
    }
  }

Fifth Step: Sort Country Names using the bottom snippet

// sort
  unique_result_for_countries = unique_result_for_countries.sort();

Sixth Step: Now, loop through “unique_result_for_countries” and create drop-down list HTML dynamically.

for (let i = 0; i < unique_result_for_countries.length; i++) {
    drop_down_items =
      drop_down_items +
      `<option value="${unique_result_for_countries[i]}">${unique_result_for_countries[i]}</option>`;
  }

Seventh Step: Now, append “drop_down_items” to “countries_drop_down” element.

// now append options to select
  countries_drop_down.innerHTML = drop_down_items;

appendCountries function code snippet

appendCountries = () => {
  // get select element using id
  let countries_drop_down = document.getElementById("covidCountries");
  let drop_down_items = "";
  // lookup object for duplicate countries
  let lookup_for_duplicate_countries = {};
  // for loop for pushing unique countries
  for (covid_state in covid_stats_global) {
    let country_name = covid_stats_global[covid_state].countryRegion;

    if (!(country_name in lookup_for_duplicate_countries)) {
      lookup_for_duplicate_countries[country_name] = 1;
      unique_result_for_countries.push(country_name);
      // console.log(country_name);
    }
  }
  // sort
  unique_result_for_countries = unique_result_for_countries.sort();
  for (let i = 0; i < unique_result_for_countries.length; i++) {
    drop_down_items =
      drop_down_items +
      `<option value="${unique_result_for_countries[i]}">${unique_result_for_countries[i]}</option>`;
  }

  // now append options to select
  countries_drop_down.innerHTML = drop_down_items;
};

The last part or function of our Covid19 Script

Add a definition of function “switchCovidStats” with parameter “countryRegion”

// append values in spans onchange event of countries
switchCovidStats = (countryRegion) => {};

Now, follow the bottom steps for writing code inside the “switchCovidStats” function:

  1. Declare and assign variables for saving total of confirmed,recovered,deaths and active cornavirus cases.
let sum_of_confirmed = 0;
let sum_of_recovered = 0;
let sum_of_deaths = 0;
let sum_of_active = 0;

2. Add the following conditions (conditions for matching the country region with the drop-down country name) and loop for calculating the sum.

Advertisements


 if (covid_stats_global) {
    for (covid_stats_global_object in covid_stats_global) {
      console.log(
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      );
      if (
        countryRegion ==
          covid_stats_global[covid_stats_global_object].combinedKey &&
        countryRegion ==
          covid_stats_global[covid_stats_global_object].countryRegion
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      } else if (
        countryRegion ==
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      }
    }
  }

3. Now, append all sum values into the original HTML elements.

document.getElementById("countryRegion").innerHTML =
    "<br><br> Country Region : " + countryRegion;
  document.getElementById("confirmed").innerHTML =
    "Confirmed : " + sum_of_confirmed;
  document.getElementById("recovered").innerHTML =
    "Recovered : " + sum_of_recovered;
  document.getElementById("deaths").innerHTML = "Deaths : " + sum_of_deaths;
  document.getElementById("active").innerHTML = "Active : " + sum_of_active;

switchCovidStats function code snippet

// append values in spans onchange event of countries
switchCovidStats = (countryRegion) => {
  // define variables for saving total for confirmed,recovered,deaths and active
  let sum_of_confirmed = 0;
  let sum_of_recovered = 0;
  let sum_of_deaths = 0;
  let sum_of_active = 0;
  if (covid_stats_global) {
    for (covid_stats_global_object in covid_stats_global) {
      console.log(
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      );
      if (
        countryRegion ==
          covid_stats_global[covid_stats_global_object].combinedKey &&
        countryRegion ==
          covid_stats_global[covid_stats_global_object].countryRegion
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      } else if (
        countryRegion ==
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      }
    }
  }
  console.log("Sum of Recovered: ->" + sum_of_recovered);
  console.log("Sum of Deaths: ->" + sum_of_deaths);
  document.getElementById("countryRegion").innerHTML =
    "<br><br> Country Region : " + countryRegion;
  document.getElementById("confirmed").innerHTML =
    "Confirmed : " + sum_of_confirmed;
  document.getElementById("recovered").innerHTML =
    "Recovered : " + sum_of_recovered;
  document.getElementById("deaths").innerHTML = "Deaths : " + sum_of_deaths;
  document.getElementById("active").innerHTML = "Active : " + sum_of_active;
  console.log("swithcing" + countryRegion);
};

The last step of this Coronavirus HTML5 widget and App script is to add event listener “change” on switching of countries drop-down “document.getElementById(“covidCountries”)” and add call switchCovidStats(document.getElementById(“covidCountries”).value);

Advertisements


// event listener change
document.getElementById("covidCountries").addEventListener("change", () => {
  switchCovidStats(document.getElementById("covidCountries").value);
});

covidStats.js file code of Coronavirus HTML5 widget and App

// let covid stats
let covid_stats_global = null;
// load json on window load
window.onload = () => {
  // create http request
  let xhttp = new XMLHttpRequest();
  // open request
  xhttp.open("GET", "https://covid19.mathdro.id/api/confirmed", false);
  // send
  xhttp.send();
  // save json in pretty form or converting JSON into object
  covid_stats_global = JSON.parse(xhttp.responseText);
  // test using console
  console.log(covid_stats_global);
  // append countries to country drop down
  appendCountries();
  //   swtiching stats
  switchCovidStats(document.getElementById("covidCountries").value);
};

let unique_result_for_countries = [];

appendCountries = () => {
  // get select element using id
  let countries_drop_down = document.getElementById("covidCountries");
  let drop_down_items = "";
  // lookup object for duplicate countries
  let lookup_for_duplicate_countries = {};
  // for loop for pushing unique countries
  for (covid_state in covid_stats_global) {
    let country_name = covid_stats_global[covid_state].countryRegion;

    if (!(country_name in lookup_for_duplicate_countries)) {
      lookup_for_duplicate_countries[country_name] = 1;
      unique_result_for_countries.push(country_name);
      // console.log(country_name);
    }
  }
  // sort
  unique_result_for_countries = unique_result_for_countries.sort();
  for (let i = 0; i < unique_result_for_countries.length; i++) {
    drop_down_items =
      drop_down_items +
      `<option value="${unique_result_for_countries[i]}">${unique_result_for_countries[i]}</option>`;
  }

  // now append options to select
  countries_drop_down.innerHTML = drop_down_items;
};

// append values in spans onchange event of countries
switchCovidStats = (countryRegion) => {
  // define variables for saving total for confirmed,recovered,deaths and active
  let sum_of_confirmed = 0;
  let sum_of_recovered = 0;
  let sum_of_deaths = 0;
  let sum_of_active = 0;
  if (covid_stats_global) {
    for (covid_stats_global_object in covid_stats_global) {
      console.log(
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      );
      if (
        countryRegion ==
          covid_stats_global[covid_stats_global_object].combinedKey &&
        countryRegion ==
          covid_stats_global[covid_stats_global_object].countryRegion
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      } else if (
        countryRegion ==
        covid_stats_global[covid_stats_global_object].combinedKey
          .split(",")
          [
            covid_stats_global[covid_stats_global_object].combinedKey.split(",")
              .length - 1
          ].trim()
      ) {
        // sum_of_confirmed
        sum_of_confirmed =
          sum_of_confirmed +
          covid_stats_global[covid_stats_global_object].confirmed;
        sum_of_recovered =
          sum_of_recovered +
          covid_stats_global[covid_stats_global_object].recovered;
        sum_of_deaths =
          sum_of_deaths + covid_stats_global[covid_stats_global_object].deaths;
        sum_of_active =
          sum_of_active + covid_stats_global[covid_stats_global_object].active;
      }
    }
  }
  console.log("Sum of Recovered: ->" + sum_of_recovered);
  console.log("Sum of Deaths: ->" + sum_of_deaths);
  document.getElementById("countryRegion").innerHTML =
    "<br><br> Country Region : " + countryRegion;
  document.getElementById("confirmed").innerHTML =
    "Confirmed : " + sum_of_confirmed;
  document.getElementById("recovered").innerHTML =
    "Recovered : " + sum_of_recovered;
  document.getElementById("deaths").innerHTML = "Deaths : " + sum_of_deaths;
  document.getElementById("active").innerHTML = "Active : " + sum_of_active;
  console.log("swithcing" + countryRegion);
};
// event listeners
document.getElementById("covidCountries").addEventListener("change", () => {
  switchCovidStats(document.getElementById("covidCountries").value);
});

I hope you enjoyed this tutorial 🙂

Test or Download this project from CodePen





Advertisements






Leave a Reply

Your email address will not be published. Required fields are marked *

× How can I help you?