Over the last few days, I have been learning from my new friend ChatGPT on how to do some webpage stuff (and create the corny screenshot above called “Welcome to HTML” it made me for this post). The wild world of ChatGPT means many more people will be able to create basic pages in the future. Below are some of the basics I have been learning about.
<body>
<div class="container">
<h1>Welcome to HTML</h1>
<p>HTML is the canvas, and you are the artist.</p>
</div>
</body>
In particular I am interested in learning about HTML, JavaScript and CSS styling. All the essentials to simple webpage design. I am very pleased with what I have been shown so far. I am rather interested in how the Java<script> can assist in making a calculation, or generating an output.
I have known about headings, body, tables in HTML. I can make a simple website, but I often lack a reason to embark on this type of learning. So I have been coming up some some useful and fun things to try out.
I decided to start with something simple. For work, I am often plagued with working out how old someone is based only on their date of birth. I therefore for some assistance and made a simple page for this which calculates the answer right in the browser.
Next, I am always needing to name documents correctly for upload to a particular system (or lack of a system). I therefore worked with ChatGPT to make a document naming tool in which I will name documents correctly for me. It required some manipulation to get the naming right, but I think we got it pretty good. Again, output is calculated locally in the user’s browser.
Next, I had some fun. In theme with my obsession with civilisation collapsing and the world ending imminently, I worked for a few days in making a form to complete which will calculate how ready you are for the apocalypse.
“You are not prepared.” – Illidan Stormrage
What I learnt
With the incredible help of ChatGPT, I will now describe each step of the scripting in Age Calculator so I can learn what is happening better. In full, it is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age Calculator</title>
</head>
<body>
<h1>Age Calculator</h1>
<form id="age-calculator-form">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" required>
<button type="button" onclick="calculateAge()">Calculate Age</button>
</form>
<h2>Age:</h2>
<p id="age"></p>
<script>
function calculateAge() {
const dobInput = document.getElementById("dob");
const dob = new Date(dobInput.value);
const now = new Date();
if (isNaN(dob.getTime())) {
alert("Please enter a valid date of birth.");
return;
}
const ageInMilliseconds = now - dob;
const ageDate = new Date(ageInMilliseconds);
const age = ageDate.getUTCFullYear() - 1970;
document.getElementById("age").textContent = `Your age is ${age} years old.`;
}
</script>
</body>
</html>
Below, I shall describe what I learn in each step. It is always best to describe things to learn them.
Function Declaration:
function calculateAge() {
This script begins by defining a function called calculateAge
. I am informed functions are like reusable blocks of code that perform a specific task when called.
Getting the Date of Birth (DOB):
const dobInput = document.getElementById("dob");
const dob = new Date(dobInput.value);
A const is a constant. In JavaScript, const
is a keyword used to declare a variable. When you declare a variable using const
, you’re telling the JavaScript engine that the identifier (variable name) you’re creating will not be reassigned to a different value after it has been initially assigned.
In this instance, I am retrieving a HTML element with the id
attribute “dob”. This was the output from the HTML form we created.
It then converts the value of the “dob” input field into a JavaScript Date object. This allows the script to work with dates.
Current Date:
const now = new Date();
It creates a new Date object called now
, representing the current date and time.
I asked ChatGPT to clarify how it knows what the current date it, when I create a Date
object without passing any arguments to it, it automatically initialises with the current date and time according to the user’s system clock and time zone settings. This means that now
will represent the current date and time at the moment when the script is executed on the user’s browser.
Checking for Valid Date of Birth:
if (isNaN(dob.getTime())) {
alert("Please enter a valid date of birth.");
return;
}
Simple enough ‘if’ statement. I want a date of birth that doesn’t calculate some error or ridiculous value. It checks if the dob
variable represents a valid date. The getTime()
method is used to get the time value of the date. If isNaN()
(is Not-a-Number) returns true, it means the input is not a valid date.
If the date of birth is not valid, it shows an alert to the user and exits the function using return
.
Calculating Age:
const ageInMilliseconds = now - dob;
const ageDate = new Date(ageInMilliseconds);
const age = ageDate.getUTCFullYear() - 1970;
I am well aware from using Microsoft Excel, Power Automate, and other things that dates are just ridiculous thing to deal with. Months with random number of days, sometimes there is a leap year.. Timezones….
And I just noticed.. Here I encounter another problem with dates… In learning about the above code used it seems this script requires subtracting 1970. I learn that the method of converting dates to UTC is a common technique because the Unix epoch, which is January 1, 1970, 00:00:00 UTC, is often used as a starting point for measuring time in computer systems. So, subtracting 1970 from the current year gives you the number of years since that epoch. At some stage I might have to explore how to calculate an age before 1970, although I mostly work with children so I had not noticed this error yet.
In any case, this calculates the age in milliseconds by subtracting the date of birth (dob
) from the current date (now
). It then creates a new Date object (ageDate
) using this age in milliseconds. Finally, it calculates the year difference between ageDate
and the year 1970 to determine the person’s age.
Displaying the Age:
document.getElementById("age").textContent = `Your age is ${age} years old.`;
This finds an HTML element with the id
attribute “age” and sets its textContent
property to display the calculated age as a message.
In summary, this script takes the user’s date of birth, converting their date of birth to milliseconds, then calculating their age by finding the difference between the current date and the DOB, and then displays the age in years on the webpage. If the DOB entered is not valid, it alerts the user to provide a valid date.
Thanks for listening.
</script>