Build a Compound Interest Rate Calculator

Web Development

In this web development tutorial you will learn how to create a compound interest calculator using HTML CSS and JavaScript

Check out the completed App here: Coumpund intrerest app

Table of content:

  1. About this project
  2. Create the compound interest calculator index.html file
  3. Style the compound interest calculator using CSS
  4. Get elements by Id from the DOM
  5. Form submission and validation
  6. Create form validation and Alert!
  7. Create a function in JavaScript to calculate the compounded interest
  8. Calculate the compounded interest rate with monthly contributions
  9. Add animation using JavaScript and CSS keyframes

About this project

In this JavaScript project you will learn:

  • Form submissions and event handling
  • Form validation with conditioning
  • JavaScript DOM manipulation
  • JavaScript Logical operates and condition

Create the compound interest calculator index.html

Create a boiler plate for your HTML and add the following HTML code to it. This consist of a h1 title class, but this is complete optional.

Next step is to create the calculator witch consists of a Form with 4 input tag with the type of number (type number insures that no accidental text is typed in) according id and placeholder and a button tag with the type of submit witch can submit the form.

In order to output the result of the compound interest, add a h3 with a class of title and id of result.

  <h1 class="title">Compound Interest Calculator 2</h1>
    <form id="CompoundInterestCalculator">
      <input
        type="number"
        id="InitialBalance"
        placeholder="Initial Balance $"
      />
      <input type="number" id="InterestRate" placeholder="Interest Rate %" />
      <input type="number" id="Years" placeholder="Years" />
      <input
        type="number"
        id="MonthlyContribution"
        placeholder="Monthly Contribution $"
      />
      <button type="submit">Calculate</button>
    </form>
    <h3 class="title" id="Result"></h3>

Style the compound interest calculator using CSS

For the design process I would strongly suggest to watch my live stream on this, simply because I walk you through my thought process and talk about the design designee that I take.

The link to the Video in further down in the post.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}
body {
  background-color: #0e2a47;
  color: #fff;
}
.title {
  font-size: 4.5rem;
  text-align: center;
  margin: 2rem 0;
}
#CompoundInterestCalculator {
  max-width: 350px;
  margin: 4rem auto;
  display: flex;

  flex-direction: column;
  gap: 15px;
  padding: 2rem;
  border-radius: 5px;
  box-shadow: 0 3px 15px 3px rgba(0, 0, 0, 0.6);
}
input {
  border: none;
  outline: none;
  padding: 0.75rem;
  border-radius: 5px;
  height: 60px;
  font-size: 1.5rem;
  background-color: #164372;
  color: #fff;
  box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.2);
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* for Firefox */
input[type="number"] {
  -moz-appearance: none;
}

button {
  cursor: pointer;
  height: 60px;
  font-size: 1.5rem;
  font-weight: 500;
  border: none;
  outline: none;

  background-color: #4ad295;
  color: #fff;
  border-radius: 5px;
}

button:hover {
  background-color: #319166;
  color: #eee;
}

button:active {
  transform: scale(0.98);
}

#Result {
  width: fit-content;
  margin: 1rem auto;
  color: #4ad295;
  padding: 0.75rem;
  border-radius: 5px;
  background-color: #164372;
  box-shadow: 0 3px 15px 3px rgba(0, 0, 0, 0.6);
}

.title.fade {
  animation: fadeIn 0.2s linear;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(-100px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

Check out the live stream for the design process on YouTube

Get elements by Id from the DOM

Let’s get started by getting the needed elements from the DOM by using there Id’s and using the getElementById selector.

To make sure we didn’t make any mistake you can console.log each one of them as you move along.

const compoundInterestCalculator = document.getElementById(
  "CompoundInterestCalculator"
);

const initialBalance = document.getElementById("InitialBalance");
const interestRate = document.getElementById("InterestRate");
const year = document.getElementById("Years");
const monthlyContribution = document.getElementById("MonthlyContribution");
const result = document.getElementById("Result");

 console.log(   
  compoundInterestCalculator,
  initialBalance,
  interestRate,
  monthlyContribution,
  result
 );

Form submission and validation

The first step in our submissions process is to actually prevent the form of submitting information to a back end that dose not exist. In order to stop this you will grab on to the event and use the preventDefault() operator on it.

Next step is to condition the submissions to a validation process. Here is where you define under what conditions the form will submit the entered information.

In this specific case we only checked if the value of the inputs are not empty then the form will proceed with the submissions process. If the even one of them is empty then the window will through a alert, prompting you to complete all field. I must mention here that the last field is acutely optional, but more on this later on.

compoundInterestCalculator.addEventListener("submit", function (e) {
  e.preventDefault();
  //   console.log(e);
  if (
    initialBalance.value === "" ||
    interestRate.value === "" ||
    year.value === ""
  ) {
    ...
  } else {
    // console.log("valid");
   
  }
});


Create form validation and Alert!

Now let’s add a alert to the application to signal to the user the necessary steps for the form validation.

alert("Complete all fields");


Create a function in javascript to calculate the compounded interest

In order to calculate the compound interest you need to aske the question, is the interest calculated taking in to consideration a monthly contribution. Depending no the answer one ore the another function will be triggered for the execution.

function calculateCompoundInterest() {
 
  if (monthlyContribution.value === "") {
    return (result.innerHTML =
      compoundInterest(initialBalance.value, interestRate.value, year.value) +
      "$");
  } else {
    return (result.innerHTML =
      compoundInterestWithContribution(
        initialBalance.value,
        interestRate.value,
        year.value,
        monthlyContribution.value
      ) + "$");
  }
}

function compoundInterest(principleAmount, interestRate, years) {
  console.log("simple compounding");
  //   A = P(1 + r / n) ^ nt;
  return (
    principleAmount * Math.pow(1 + interestRate / 100 / 12, 12 * years)
  ).toFixed(2);
}


Calculate the compounded interest rate with monthly contributions

If the user chooses to also contribute a regular ( each month of the year for as long as it takes) monthly sum to the initial investment, then the formula for calculating the compounded interest changes with a addition on a monthly contribution.

Because you already conditioned your evaluation in the calculateCompoundInterest() function the correct execution will take effect upon a re-submission of the form.

function compoundInterestWithContribution(
  principleAmount,
  interestRate,
  years,
  monthlyContribution
) {
  return (
    principleAmount * Math.pow(1 + interestRate / 100 / 12, 12 * years) +
    (monthlyContribution *
      (Math.pow(1 + interestRate / 100 / 12, 12 * years) - 1)) /
      (interestRate / 100 / 12)
  ).toFixed(2);
}


Add animation using JavaScript and CSS keyframes

If you take a look in you CSS you will find a “fade” class that is added to the “title” class. This means then when the class of title also has the class of fade then the mentioned properties will take effect. All you need to do now is add the fade class to the title class in JavaScript.

Here’s how you do it.

Using the result variable we can add or remove classes from its class list in JavaScript. This will be triaged on the submit event.

The only problem that we encounter is on a recalculation the effect has already taken place because the class was added in the initial execution of the function.

In order to salve this problem you can remove the class from the result variable immediately after it was added using a setTimeout() and delaying the removal by 1000 milliseconds.

 result.classList.add("fade");
  setTimeout(function () {
    result.classList.remove("fade");
  }, 1000);

For more information check out the video tutorial on YouTube.

Watch the full tutorial on YouTube and get step by step excellent education information about this project.

Coming out today!


Want to become a web developer ?

Get complete web development courses on HTML, CSS , JavaScript, Bootstrap, Visual Studio Code, Responsive design and much more…

Love Podcast about web development?

Refactoring coming up !!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.