Learn how to create a simple salary calculator using HTML, CSS, and JavaScript. Follow our step-by-step guide to build this project easily.
Table of Contents
A salary calculator is a useful tool that calculates monthly, yearly, and overtime earnings. This project is simple and perfect for beginners learning HTML, CSS, and JavaScript. In this blog, we’ll guide you through creating a salary calculator step by step.
Prerequisites
Before starting, ensure you have:
- A basic understanding of HTML, CSS, and JavaScript.
- A code editor like Visual Studio Code.
- A browser to test your project.
Source Code
Step 1 (HTML Code):
Add the basic structure for the salary calculator.
Here's a breakdown of the code:
1. HTML Document Setup
<!DOCTYPE html>
: Declares the document as HTML5.<html lang="en">
: Specifies the language as English.<head>
: Contains metadata and links to external stylesheets.<meta charset="UTF-8">
: Sets the character encoding to UTF-8 for proper text rendering.<meta name="viewport" content="width=device-width, initial-scale=1.0">
: Ensures responsive design on different devices.<title>
: Sets the title of the webpage.- Bootstrap CSS: Adds Bootstrap for layout and styling.
- Custom CSS: Links to a local stylesheet (
styles.css
) for additional styling.
2. Body Layout
Container
<div class="container mt-5">
: A Bootstrap container with a top margin for spacing.<h1>
: The main heading "Salary Calculator" is centered and styled with a bottom margin.
3. Form Section
Left Column
<div class="col-md-6">
: A column occupying 6 out of 12 grid units for medium and larger screens.<form id="salaryForm">
: A form for user input.
Form Fields
- Job: Text input for the job title.
- Work Hours and Work Week: Two number inputs for daily work hours and weekly workdays.
- Gross Monthly Salary: Number input for entering gross salary.
- Tax Percentage: Number input for specifying tax percentage.
- Overtime Details:
- Overtime Hours: Number input for weekly overtime hours.
- Overtime Rate: Number input for hourly overtime rate.
- Buttons:
- Calculate Salary: A button to trigger the calculation.
- Clear: A button to reset the form.
4. Results Section
Right Column
<div class="col-md-6">
: Another column occupying 6 out of 12 grid units.<div id="results">
: A container for displaying the calculated results.
Results Display
- Title: A heading displaying the job title dynamically.
- Table: A Bootstrap-styled table to display calculated salary details:
- Hourly, daily, and monthly gross salary.
- Tax deductions and net salary.
- Yearly net salary.
- Total overtime earnings.
- Total earnings including overtime.
5. JavaScript Link
<script src="script.js"></script>
: Links to an external JavaScript file (script.js
) to handle form submissions and calculations.
Step 2 (CSS Code):
Add styles to make the calculator visually appealing.
Here's a breakdown:
1. Font Import
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap');
- Purpose: Imports the Poppins font from Google Fonts with a weight of 500 (medium).
- Display: The
display=swap
ensures the fallback font is used until Poppins is fully loaded.
2. Universal Selector
* {
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
*
: Applies the rules to all elements.margin: 0; padding: 0;
: Resets default browser margins and paddings for consistency.font-family
: Sets the default font to Poppins with a fallback to sans-serif.
3. Body Styling
body {
display: flex;
justify-content: center;
align-items: center;
background: #825CFF;
}
display: flex;
: Enables flexbox for the body to align content.justify-content: center; align-items: center;
: Centers content both horizontally and vertically.background: #825CFF;
: Sets the background color to a purple shade.
4. Container Styling
.container {
background: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 900px;
margin: 30px auto;
}
background
: White background for the container.border-radius: 8px;
: Rounds the corners.box-shadow
: Adds a soft shadow for depth.padding: 20px;
: Adds inner spacing.max-width: 900px;
: Restricts the container's width to 900px.margin: 30px auto;
: Centers the container with a top margin.
5. Heading Styling
h1 {
color: #825CFF;
}
color
: Sets the text color of headings to the same purple shade as the background.
6. Results Section
#results {
background-color: #f1f1f1;
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
background-color: #f1f1f1;
: Light gray background for the results section.border-radius: 8px;
: Rounds the corners.padding: 15px;
: Adds inner spacing.box-shadow
: Adds a subtle shadow for depth.
7. Table Styling
.table {
margin-top: 10px;
background-color: #ffffff;
}
margin-top: 10px;
: Adds spacing above the table.background-color
: White background for the table.
8. Button Styling
General Button Styling
.btn {
margin-top: 10px;
}
margin-top: 10px;
: Adds spacing above buttons.
Primary Button
.btn-primary {
background-color: #825CFF;
border-color: #825CFF;
}
.btn-primary:hover {
background-color: #7348ff;
border-color: #7348ff;
}
background-color
: Sets the default color to purple.border-color
: Matches the button's border with the background.- Hover State: Changes the color to a slightly darker purple on hover.
Secondary Button
.btn-secondary {
background-color: #6c757d;
border-color: #6c757d;
}
background-color
: Sets a gray background for secondary buttons.border-color
: Matches the button's border with the background.
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap');
* {
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #825CFF;
}
.container {
background: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 900px;
margin: 30px auto;
}
h1 {
color: #825CFF;
}
#results {
background-color: #f1f1f1;
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.table {
margin-top: 10px;
background-color: #ffffff;
}
.btn {
margin-top: 10px;
}
.btn-primary {
background-color: #825CFF;
border-color: #825CFF;
}
.btn-primary:hover{
background-color: #7348ff;
border-color: #7348ff;
}
.btn-secondary {
background-color: #6c757d;
border-color: #6c757d;
}
Step 3 (JavaScript Code):
Implement the calculation logic in JavaScript.
Here's an explanation of the code:
1. Event Listener for "Calculate" Button
document.getElementById("calculateButton").addEventListener("click", function () {
- Purpose: Adds a click event listener to the button with the ID
calculateButton
. - Functionality: When clicked, it calculates salary details based on user inputs and displays them.
2. Retrieving Input Values
const job = document.getElementById("job").value || "______";
const workHour = parseInt(document.getElementById("workHour").value) || 0;
const workWeek = parseInt(document.getElementById("workWeek").value) || 0;
const grossSalary = parseFloat(document.getElementById("netSalary").value) || 0;
const tax = parseFloat(document.getElementById("tax").value) || 0;
const overtimeHours = parseInt(document.getElementById("overtimeHours").value) || 0;
const overtimeRate = parseFloat(document.getElementById("overtimeRate").value) || 0;
- Input Fields: Retrieves values from form fields using their IDs.
- Default Values: If a field is empty or invalid, a default value (
"______"
for text,0
for numbers) is used.
- Default Values: If a field is empty or invalid, a default value (
- Parsing: Converts string inputs to numbers using
parseInt
(for integers) orparseFloat
(for decimals).
3. Calculations
const monthlyTaxDeduction = (grossSalary * tax) / 100;
const netMonthlySalary = grossSalary - monthlyTaxDeduction;
const hourlySalary = netMonthlySalary / (workWeek * workHour * 4);
const dailySalary = hourlySalary * workHour;
const yearlySalary = netMonthlySalary * 12;
const overtimeEarnings = overtimeHours * overtimeRate * 4;
const totalEarnings = yearlySalary + overtimeEarnings;
- Monthly Tax Deduction: Calculates tax based on the gross salary.
- Net Monthly Salary: Subtracts tax from the gross salary.
- Hourly Salary: Divides net monthly salary by total working hours in a month (
workWeek * workHour * 4
). - Daily Salary: Multiplies hourly salary by daily working hours.
- Yearly Salary: Multiplies net monthly salary by 12.
- Overtime Earnings: Calculates total overtime pay for the month.
- Total Earnings: Adds yearly salary and overtime earnings.
4. Displaying Results
document.getElementById("jobTitle").textContent = job;
document.getElementById("hourly").textContent = `$${hourlySalary.toFixed(2)}`;
document.getElementById("daily").textContent = `$${dailySalary.toFixed(2)}`;
document.getElementById("monthlyGross").textContent = `$${grossSalary.toFixed(2)}`;
document.getElementById("taxDeduction").textContent = `-$${monthlyTaxDeduction.toFixed(2)}`;
document.getElementById("monthlyNet").textContent = `$${netMonthlySalary.toFixed(2)}`;
document.getElementById("yearly").textContent = `$${yearlySalary.toFixed(2)}`;
document.getElementById("overtimeEarnings").textContent = `$${overtimeEarnings.toFixed(2)}`;
document.getElementById("totalEarnings").textContent = `$${totalEarnings.toFixed(2)}`;
- Purpose: Updates the content of various elements with the calculated results.
- Formatting:
toFixed(2)
: Ensures monetary values are displayed with two decimal places.$
: Adds a dollar sign to indicate currency.
5. Event Listener for "Clear" Button
document.getElementById("clearButton").addEventListener("click", function () {
- Purpose: Adds a click event listener to the button with the ID
clearButton
. - Functionality: Resets the form and clears displayed results.
6. Resetting Form and Display
document.getElementById("salaryForm").reset();
document.getElementById("jobTitle").textContent = "______";
document.getElementById("hourly").textContent = "$0";
document.getElementById("daily").textContent = "$0";
document.getElementById("monthlyGross").textContent = "$0";
document.getElementById("taxDeduction").textContent = "$0";
document.getElementById("monthlyNet").textContent = "$0";
document.getElementById("yearly").textContent = "$0";
document.getElementById("overtimeEarnings").textContent = "$0";
document.getElementById("totalEarnings").textContent = "$0";
reset()
: Clears all form inputs.- Updating Text Content: Resets displayed results to default values.
document.getElementById("calculateButton").addEventListener("click", function () {
const job = document.getElementById("job").value || "______";
const workHour = parseInt(document.getElementById("workHour").value) || 0;
const workWeek = parseInt(document.getElementById("workWeek").value) || 0;
const grossSalary = parseFloat(document.getElementById("netSalary").value) || 0;
const tax = parseFloat(document.getElementById("tax").value) || 0;
const overtimeHours = parseInt(document.getElementById("overtimeHours").value) || 0;
const overtimeRate = parseFloat(document.getElementById("overtimeRate").value) || 0;
const monthlyTaxDeduction = (grossSalary * tax) / 100;
const netMonthlySalary = grossSalary - monthlyTaxDeduction;
const hourlySalary = netMonthlySalary / (workWeek * workHour * 4);
const dailySalary = hourlySalary * workHour;
const yearlySalary = netMonthlySalary * 12;
const overtimeEarnings = overtimeHours * overtimeRate * 4;
const totalEarnings = yearlySalary + overtimeEarnings;
document.getElementById("jobTitle").textContent = job;
document.getElementById("hourly").textContent = `$${hourlySalary.toFixed(2)}`;
document.getElementById("daily").textContent = `$${dailySalary.toFixed(2)}`;
document.getElementById("monthlyGross").textContent = `$${grossSalary.toFixed(2)}`;
document.getElementById("taxDeduction").textContent = `-$${monthlyTaxDeduction.toFixed(2)}`;
document.getElementById("monthlyNet").textContent = `$${netMonthlySalary.toFixed(2)}`;
document.getElementById("yearly").textContent = `$${yearlySalary.toFixed(2)}`;
document.getElementById("overtimeEarnings").textContent = `$${overtimeEarnings.toFixed(2)}`;
document.getElementById("totalEarnings").textContent = `$${totalEarnings.toFixed(2)}`;
});
document.getElementById("clearButton").addEventListener("click", function () {
document.getElementById("salaryForm").reset();
document.getElementById("jobTitle").textContent = "______";
document.getElementById("hourly").textContent = "$0";
document.getElementById("daily").textContent = "$0";
document.getElementById("monthlyGross").textContent = "$0";
document.getElementById("taxDeduction").textContent = "$0";
document.getElementById("monthlyNet").textContent = "$0";
document.getElementById("yearly").textContent = "$0";
document.getElementById("overtimeEarnings").textContent = "$0";
document.getElementById("totalEarnings").textContent = "$0";
});
Final Output:
Conclusion:
Building a salary calculator using HTML, CSS, and JavaScript is a valuable project that enhances your web development skills. This simple yet powerful tool can be customized further to include additional features such as tax calculations, currency conversions, or data saving. By following the steps outlined in this guide, you can easily create a functional salary calculator and improve your ability to build dynamic web applications. Keep exploring and refining your skills to create even more advanced and interactive projects.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊