Coding challenge #3 (beginner level) - Leap year checker


Topic: Coding challenge #3 (beginner level) - Leap year checker
Published 12.02.2019 Updated 18.02.2019

Michal Szymanski posted a week ago

Introduction

In this tutorial, you will learn how to create Leap year checker. This is a tool that can check if a year typed by the user is a leap year.

SEE THE FINAL RESULT

What is a leap year?

A leap year is a year containing one additional day added to keep the calendar year synchronized with the astronomical or seasonal year. Because seasons and astronomical events do not repeat in a whole number of days, calendars that have the same number of days in each year drift over time with respect to the event that the year is supposed to track. By inserting an additional day or month into the year, the drift can be corrected. A year that is not a leap year is called a common year. Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the year 2000 is.

What exactly you will learn:

  • Events
  • Collecting data from the user
  • Inputs
  • Conditional statements
  • Comparison and logical operators
  • Adding and removing classes

Note 1: This particular tool isn't the most important here. We will use it as a practical example, which let you practice your basic javascript knowledge.

Note 2: For purpose of this tutorial, I have complicated a bit this example. There are ways to write it faster, shorter and simpler. But then you wouldn't learn a many important things.


MDB Coding Challenge

This tutorial is part of the MDB Coding Challenge.

It is an initiative that helps novice programmers learn programming through practical examples and creative challenges.

LEARN MORE ABOUT MDB CODING CHALLENGE

Requirements

To follow this tutorial you need a basic knowledge of HTML, CSS, JavaScript and MDBootstrap .

If you don't know these technologies or you would like to repeat the knowledge about them, I recommend you to read our previous tutorials first.

They are short, simple and free.

START HTML TUTORIAL START CSS TUTORIAL START JAVASCRIPT TUTORIAL

Useful resources (not required but recommended)

START MDBOOTSTRAP TUTORIAL MDBOOTSTRAP ANIMATIONS EXAMPLES

Let's get started!

Step 1 - creating a basic HTML structure

Add the following HTML code to your project. There is nothing special here - just a few HTML elements with specified ID's that we will use later in our JavaScript code.

Note: If you need a detailed explanation of this HTML code, that means that you should go back to the basic tutorials that I have listed above.

<!-- Input to take a value from the user -->
<input id="yearInput" type="text">

<!-- Action button -->
<button id="btnStart">Click to check</button>

<!-- Heading to render the result -->
<h2 id="demo"></h2>

Step 2 - onClick event

At the beginning we catch an ID of the #btnStart. Then we use onClick event to launch all the other code.

// On click event that launch the mainFunction
document.getElementById('btnStart').onclick = function mainFunction() {

}

Step 3 - input value

To collect a data typed by the user we need to catch an ID of the input and then use .value method to get to store the value in the variable.

// On click event that launch the mainFunction
document.getElementById('btnStart').onclick = function mainFunction() {

  // Get the value from the input
  let year = document.getElementById("yearInput").value;

}

Step 4 - the logic of the checker function

How exactly do we check if the given year is a leap year?

To implement the schema above we will execute 3 steps:

  1. First check if is it divisible by 100 and it's not divisible by 400 (if true - return "it's not a leap year")
  2. Then check if is it divisible by 4 (if true - return "it's a leap year")
  3. Then check if it's not divisible by 4 (if true - return "it's not a leap year")

Step 5 - check function with an conditional statement

We will write a function containing conditional statements. This conditional statement will be main logic of our app - it will check if the given year is a leap year.

checkFunction will accept one parameter year - which is a value typed by the user in the input.

// On click event that launch the mainFunction
document.getElementById('btnStart').onclick = function mainFunction() {

  // Get the value from the input
  let year = document.getElementById("yearInput").value;

  // Checker function that contains conditional statemens
  function checkFunction(year) {

    // Check if the given year is a leap year
    if (year % 100 === 0 && year % 400 !== 0) {
      return year + " is not a leap year";
    } else if (year % 4 === 0) {
      return year + " is a leap year";
    } else if (year % 4 !== 0) {
      return year + " is not a leap year";
    }
  }

}

Step 6 - putting the result in the heading

At the end we need to catch the heading with an ID demo and put the result of the checkFunction inside, by using .innerHTML method.

We will invoke the checkFUnction with the year argument.

Note: A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. Parameter is variable in the declaration of function. Argument is the actual value of this variable that gets passed to function.

// On click event that launch the mainFunction
document.getElementById('btnStart').onclick = function mainFunction() {

  // Get the value from the input
  let year = document.getElementById("yearInput").value;

  // Checker function that contains conditional statemens
  function checkFunction(year) {

    // Check if the given year is a leap year
    if (year % 100 === 0 && year % 400 !== 0) {
      return year + " is not a leap year";
    } else if (year % 4 === 0) {
      return year + " is a leap year";
    } else if (year % 4 !== 0) {
      return year + " is not a leap year";
    }
  }

  // putting the result in the heading
  document.getElementById('demo').innerHTML = checkFunction(year);
}

The entire code looks like this:

<!-- Input to take a value from the user -->
<input id="yearInput" type="text">

<!-- Action button -->
<button id="btnStart">Click to check</button>

<!-- Heading to render the result -->
<h2 id="demo"></h2>
// On click event that launch the mainFunction
document.getElementById('btnStart').onclick = function mainFunction() {

  // Get the value from the input
  let year = document.getElementById("yearInput").value;

  // Checker function that contains conditional statemens
  function checkFunction(year) {

    // Check if the given year is a leap year
    if (year % 100 === 0 && year % 400 !== 0) {
      return year + " is not a leap year";
    } else if (year % 4 === 0) {
      return year + " is a leap year";
    } else if (year % 4 !== 0) {
      return year + " is not a leap year";
    }
  }

  // putting the result in the heading
  document.getElementById('demo').innerHTML = checkFunction(year);
}

Styling

To create a beautiful material form like in the demo at the beginning of this tutorial we will use MDBootstrap library.

Note: I am not going to explain here how does it exactly works. If you are new to MDBootstrap follow our previous tutorial. There I explain in details every aspect of MDBootstrap, Bootstrap and Responsive Web Design in general.

MDBOOTSTRAP FULL TUTORIAL

Step 1 - centered grid column and card

We will combine bootstrap grid and flexbox to create responsive and centered column. Inside the column we will place a card with the material form within.

<!-- Grid container -->
<div class="container my-4">

  <!--Grid row-->
  <div class="row d-flex justify-content-center">

    <!--Grid column-->
    <div class="col-md-6">

      <!-- Material card -->
      <div class="card">

        <!-- Header -->
        <h5 class="card-header info-color white-text text-center py-4">
          <strong>Lean year checker</strong>
        </h5>

        <!--Card content-->
        <div class="card-body">

          <!-- Material input -->
          <div class="md-form md-outline mt-1 mb-4">
            <input id="yearInput" type="text" class="form-control">
            <label for="yearInput">Type a year to check if is it a leap year</label>
          </div>

          <!-- Action button -->
          <button id="btnStart" class="btn btn-outline-info btn-rounded btn-block waves-effect z-depth-0 mb-2">Click
            to check</button>

        </div>

      </div>
      <!-- Material card -->

    </div>
    <!--Grid column-->

  </div>
  <!--Grid row-->


  <!-- Heading element to display the result -->
  <h2 id="demo" class="my-5 h2 text-center" style="color: #666;"></h2>

</div>
<!-- Grid container -->

Step 2 - adding animation

To add an animation we will use one of the predefined animation classes from MDBootstrap.

We also need to remove the class after the animation is finished. Otherwise, it will animate only once.

We use setTimeout method to prevent removing animation before animation is finished.

// Adding animation class
function addAnimation() {
  document.getElementById('demo').innerHTML = checkFunction(year);
  document.getElementById('demo').classList.add("animated", "fadeInUp");

  // Remove animation class
  setTimeout(function () {
    document.getElementById('demo').classList.remove("animated", "fadeInUp");
  }, 1000);
}
addAnimation();

Congratulations, you made it!

The entire code is available here:

FINAL CODE

Write
Please insert min. 20 characters.