Today I was trying to figure out how to make a Chinese zodiac calculator for the year 1830. It sounded like a fun little project, so I dove right in.
Getting Started
First, I opened up my code editor and started a new HTML file. I added the basic structure, you know, the usual <!DOCTYPE html>
, <html>
, <head>
, and <body>
tags. Nothing fancy, just the bare bones to get things rolling.
Setting Up the Input
Next, I needed a way for users to input the year. I created a simple form with an input field for the year and a submit button. I gave the input field an ID so I could grab its value later with JavaScript. It looked something like this:
<form id="zodiacForm">
<label for="yearInput">Enter a year:</label>
<input type="number" id="yearInput" name="yearInput" value="1830">
<button type="submit">Calculate Zodiac</button>
</form>
The JavaScript Magic
Now came the fun part – writing the JavaScript. I added a <script>
tag at the end of my <body>
. First, I needed to prevent the form from refreshing the page when submitted. I added an event listener for the form’s submit event and used to stop the default behavior.
Then, I grabbed the value entered in the input field using *("yearInput").value
. I made sure to convert this to a number using parseInt()
since it comes as a string by default.
Calculating the Zodiac
This was the tricky part. I figured out that the Chinese zodiac follows a 12-year cycle. I needed to find the remainder when the input year is divided by 12. I used the modulo operator () for this. I subtracted 3 from the year. And I used a switch
statement to determine the zodiac animal based on the remainder.
- If the remainder is 0, it’s a Dog.
- 1 would be pig
- 2 would be rat
- 3 would be ox
- 4 would be tiger
- 5 would be rabbit
- 6 would be dragon
- 7 would be snake
- 8 would be horse
- 9 would be goat
- 10 would be monkey
- 11 would be rooster
Displaying the Result
Finally, I needed to show the result to the user. I added a <div>
to my HTML to display the output. I gave it an ID so I could target it with JavaScript. Then, back in my JavaScript, I grabbed this <div>
using and set its textContent
to the calculated zodiac animal. For 1830, it showed “Dog”.
Wrapping Up
And that’s it! It wasn’t too complicated, but it was a neat little exercise. Now, anyone can input a year, specifically 1830, and find out the corresponding Chinese zodiac animal. It’s not perfect, and there’s probably room for improvement, but it works!