Skip to main content

TimeCalc: The Ultimate Tool for Time Calculations Made Easy

A Step-by-Step Guide




Create an Awesome Time Calculator web application!

Introduction:

In this project, we will build a web application that allows users to input times in the format "HH:MM:SS" and perform calculations. Get ready to streamline your time calculations and make your life easier with our intuitive and efficient web app.


Figure:
Preview (tap to see clearly)



Prerequisites:

Before diving into this tutorial, ensure you have the following prerequisites:
  1. Basic Knowledge of HTML:
    • Understanding the structure and syntax of HTML (HyperText Markup Language) is essential for creating the foundation of web pages.
  2. Fundamentals of CSS:
    • Familiarize yourself with CSS (Cascading Style Sheets) concepts such as selectors, properties, and values.
    • Learn how to style HTML elements, apply layouts, and manage visual presentation on web pages.
  3. Understanding JavaScript:
    • Gain a basic understanding of JavaScript, the programming language of the web.
    • Learn about variables, data types, functions, control structures, and DOM manipulation.

By mastering these fundamental concepts, you'll be well-equipped to follow along with the tutorial and expand your skills in web development.

If you have any questions or encounter challenges while working through this tutorial, don't hesitate to reach out! I'm here to help you succeed. Feel free to leave a comment below, and I'll get back to you as soon as possible.

Your feedback and inquiries are valuable, and I'm more than happy to assist you on your coding journey.
Happy coding!




Here's a step-by-step breakdown of our code:

  1. HTML Structure:
    • Define the basic HTML structure including the <!DOCTYPE> declaration, <html>, <head>, and <body> tags.
    • Set the character set and viewport meta tags.
    • Include a title for the webpage.
    • Link to an external stylesheet (style.css) for styling purposes.
    • Create a container <div> with an id of "container" to hold the content of the web application.
    • Inside the container, create elements for the heading, form, buttons for add or remove time section, result display, and another button for calculating the result.
    • And last link to an external script (script.js) for logical functionality.
  2. CSS Styling:
    • Apply general styling to reset margins, padding, font size, and font family for all elements.
    • Set the background color for the body and center its content horizontally.
    • Style the container with a specific width, background color, border radius, and padding.
    • Customize the appearance of various elements such as the heading, input sections, buttons, and result display.
  3. JavaScript Functionality:
    • Define global variables and initialize the input_section_list array with default section IDs.
    • Use DOMContentLoaded event listener to execute JavaScript code after the HTML content has been fully loaded.
    • Create functions to add or remove input sections dynamically (addMore, remove).
    • Implement functions to increment or decrement time values within each input section (incrementValue, decrementValue).
    • Create a function (createInputSection) to dynamically generate input sections with hour, minute, and second fields.
    • Implement the calculate function to compute the total time based on the input values and display the result.
    • Define helper functions (sumArray, organizeTime) to perform calculations and format the total time output.
  4. Event Handling:
    • Utilize event attributes (onclick) within HTML elements to trigger specific JavaScript functions when interacting with buttons.
  5. Overall Structure:
    • The HTML provides the structure and content of the web application.
    • CSS styles enhance the visual appearance and layout of the elements.
    • JavaScript adds interactivity and functionality to the application, allowing users to dynamically add input sections, input time values, perform calculations, and display results.


Unlock the Power of Color: Exploring the Vibrant Palette of Our Web Application Project

Here's the colors we will use in our application.
  1. #000000 (black)
  2. #2A2A2A (dark gray)
  3. #FFFFFF (white)
  4. FF555F (pinkish-red)
  5. #3827B1 (dark purple)
Which look something like this.



Figure:
Vibrant Color Palette


HTML Structure of Our Project:

Code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Time Calc</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="container">
            <p id="heading">Add Time</p>
            <form>
                <!--all input section goes here-->
            </form>
            <div id="remove-and-add">
                <button onclick="remove()">Remove</button>
                <button onclick="addMore()">Add More</button>
            </div>
            <p id="result">Result</p>
            <button id="calculate" onclick="calculate()">Calculate</button>
        </div>
        <script src="script.js"></script>
    </body>
</html>




CSS Styling of Our Project:

Code:

* {
     margin: 0;
     padding: 0;
     font-size: 14px;
     font-family: Arial;
 }

body {
    background-color: black;
    display: flex;
    justify-content: center;
    margin-top: 60px;
}

#container {
    width: 300px;
    background-color: #2A2A2A;
    border-radius: 24px;
    padding: 15px;
    display: flex;
    flex-direction: column;
}

#heading {
    color: #FF555F;
    font-weight: bold;
    text-align: center;
    font-size: 1.5em;
    padding: 10px;
}

.input-section {
    border: 1px solid white;
    border-radius: 24px;
    padding: 5px;
    display: flex;
    justify-content: center;
    margin-bottom: 25px;
}

.hour-section, .minute-section, .second-section {
    width: 40px;
    background-color: black;
    border-radius: 10px;
    margin: 5px;
    display: flex;
    flex-direction: column;
    padding: 10px;
}

.increment-section, .decrement-section {
    background-color: #3827B1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 1.2em;
}

.increment-section:hover {
    background-color: #FF555F;
}

.decrement-section:hover {
    background-color: #FF555F;
}

.input-section input {
    margin: 5px 0;
    text-align: center;
    color: #2A2A2A;
}

.time-label {
    color: white;
    margin-top: 10px;
    text-align: center;
    font-weight: bold;
}

#remove-and-add {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

#result {
    background-color: white;
    text-align: center;
    border-radius: 4px;
    padding: 5px;
    margin-bottom: 10px;
}

button {
    background-color: #FF555F;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 5px;
    font-size: 1.1em;
}

button:hover {
    background-color: #FF7881;
}

#calculate {
    font-weight: bold;
    margin-bottom: 20px;
}




Javascript Logic of Our Project:

Code:

// list variable for input sections (default two section)
let input_section_list = ["section-1", "section-2"];


document.addEventListener("DOMContentLoaded", () => {
    // loop for create create input section (default 2 section)
    for (let section of input_section_list) {
        createInputSection(section);
    }
});



// function for add more section
function addMore () {
    const new_section = `section-${input_section_list.length + 1}`;
    input_section_list.push(new_section);
    createInputSection(new_section);
}


// function for remove last section
function remove () {
    const remove = input_section_list.pop();
    const remove_el = document.getElementById(remove);
    remove_el.remove();
}





// function for increase value of a specific section and it's time
function incrementValue(el) {
    const input_element = el.parentElement.querySelector("input");
    input_element.value ++;
    // condition for
    if (input_element.className !== "hour") {
        if (input_element.value > 59) {
            input_element.value = 0;
        }
    }
}


// function for decrease value of a specific section and it's time
function decrementValue(el) {
    const input_element = el.parentElement.querySelector("input");
    input_element.value --;
    // condition for limit the value from 0 to infinite
    if (input_element.value < 0) {
        if (input_element.className !== "hour") {
            input_element.value = 59;
        }else {
            input_element.value = 0;
        }
    }
}






// function for create a input section
function createInputSection (section_id) {
    // get form element
    const form_el = document.querySelector("form");
    // create input section div element
    const input_section_el = document.createElement("div");
    // set class and id attribute
    input_section_el.setAttribute("class", "input-section");
    input_section_el.setAttribute("id", section_id);
    // append it to container div
    form_el.append(input_section_el);
    
    const time_section_list = ["hour", "minute", "second"];
    // loop
    for (let time of time_section_list) {
        // create time element of div
        const time_el = document.createElement("div");
        // set class attribute for it
        time_el.setAttribute("class", `${time}-section`);
        // append it to input_section_el
        input_section_el.append(time_el);
        // create 4 element
        const increment_el = document.createElement("div");
        const decrement_el = document.createElement("div");
        const input_el = document.createElement("input");
        const p_el = document.createElement("p");
        // set class attribute for div
        increment_el.setAttribute("class", "increment-section");
        decrement_el.setAttribute("class", "decrement-section");
        // set function attribute for div
        increment_el.setAttribute("onclick", "incrementValue(this)");
        decrement_el.setAttribute("onclick", "decrementValue(this)");
        // add text for div
        increment_el.innerText = "+";
        decrement_el.innerText = "-";
        // ser attribute for input
        input_el.setAttribute("type", "number");
        input_el.setAttribute("value", "00");
        input_el.setAttribute("class", time);
        input_el.setAttribute("name", `${section_id}-${time}`);
        // set attribute for p
        p_el.setAttribute("class", "time-label");
        // add text for p
        if (time === "hour") {
            p_el.innerText = "HH";
        }else if (time === "minute") {
            p_el.innerText = "MM";
        }else {
            p_el.innerText = "SS";
        }
        // append 4 elements in time_el
        time_el.append(increment_el);
        time_el.append(input_el);
        time_el.append(decrement_el);
        time_el.append(p_el);
    }
}





// function for calculate the final result and show
function calculate () {
    const form_el = document.querySelector("form");
    const form_data = new FormData (form_el);
    
    let hour_list = [];
    let minute_list = [];
    let second_list = [];
    
    for (let data of form_data) {
        if (data[0].includes("hour")) {
            hour_list.push(parseInt(data[1]));
        }else if (data[0].includes("minute")) {
            minute_list.push(parseInt(data[1]));
        }else if (data[0].includes("second")) {
            second_list.push(parseInt(data[1]));
        }
    }
    
    const total_hours = sumArray(hour_list);
    const total_minutes = sumArray(minute_list);
    const total_seconds = sumArray(second_list);
    
    const result = organizeTime(total_hours, total_minutes, total_seconds);
    
    // get result element
    const result_el = document.getElementById("result");
    result_el.innerText = result;
}





// function for add all elements in a specific array. In this case (arr)
function sumArray(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}




// function for format time and return as string
function organizeTime(total_hours, total_minutes, total_seconds) {
    // Calculate the total time in seconds
    let total_seconds_all = total_hours * 3600 + total_minutes * 60 + total_seconds;

    // Calculate hours, minutes, and seconds
    let hours = Math.floor(total_seconds_all / 3600);
    let remaining_seconds = total_seconds_all % 3600;
    let minutes = Math.floor(remaining_seconds / 60);
    let seconds = remaining_seconds % 60;

    // Format the hours, minutes, and seconds with leading zeros if necessary
    let formatted_hours = hours < 10 ? '0' + hours : hours;
    let formatted_minutes = minutes < 10 ? '0' + minutes : minutes;
    let formatted_seconds = seconds < 10 ? '0' + seconds : seconds;

    // Return the organized time as a string
    return `${formatted_hours}:${formatted_minutes}:${formatted_seconds}`;
}

Here's a breakdown of our JavaScript code:

1. Variable Declaration:

input_section_list: Initializes an array with default section IDs.
// list variable for input sections (default two section)
let input_section_list = ["section-1", "section-2"];

2. Event Listener:

DOMContentLoaded: Listens for when the DOM content is loaded, then executes the callback function.
document.addEventListener("DOMContentLoaded", () => {
    // loop for create input section (default 2 section)
    for (let section of input_section_list) {
        createInputSection(section);
    }
});
You will see this function createInputSection() later in detail.

3. Functions:

add_section(): Adds a new input section by creating a new section ID, pushing it into the input_section_list, and calling createInputSection().
// function for add more section
function add_section () {
    const new_section = `section-${input_section_list.length + 1}`;
    input_section_list.push(new_section);
    createInputSection(new_section);
}

remove_section(): Removes the last input section by popping the last section ID from input_section_list and removing the corresponding element from the DOM.
// function for remove last section
function remove_section () {
    const removed = input_section_list.pop();
    const remove_el = document.getElementById(removed);
    remove_el.remove();
}

incrementValue(el): Increases the value of a specific input element within a section, with additional logic to handle hour, minute, and second values.
// function for increase value of a specific section and it's time
function incrementValue(el) {
    const input_element = el.parentElement.querySelector("input");
    input_element.value ++;
    // condition for
    if (input_element.className !== "hour") {
        if (input_element.value > 59) {
            input_element.value = 0;
        }
    }
}

decrementValue(el): Decreases the value of a specific input element within a section, with similar logic as incrementValue().
// function for decrease value of a specific section and it's time
function decrementValue(el) {
    const input_element = el.parentElement.querySelector("input");
    input_element.value --;
    // condition for limit the value from 0 to infinite
    if (input_element.value < 0) {
        if (input_element.className !== "hour") {
            input_element.value = 59;
        }else {
            input_element.value = 0;
        }
    }
}

createInputSection(section_id): Dynamically creates input sections within a form, each containing hour, minute, and second elements, along with buttons for incrementing and decrementing values.
// function for create a input section
function createInputSection (section_id) {
    // get form element
    const form_el = document.querySelector("form");
    // create input section div element
    const input_section_el = document.createElement("div");
    // set class and id attribute
    input_section_el.setAttribute("class", "input-section");
    input_section_el.setAttribute("id", section_id);
    // append it to container div
    form_el.append(input_section_el);
    
    const time_section_list = ["hour", "minute", "second"];
    // loop
    for (let time of time_section_list) {
        // create time element of div
        const time_el = document.createElement("div");
        // set class attribute for it
        time_el.setAttribute("class", `${time}-section`);
        // append it to input_section_el
        input_section_el.append(time_el);
        // create 4 element
        const increment_el = document.createElement("div");
        const decrement_el = document.createElement("div");
        const input_el = document.createElement("input");
        const p_el = document.createElement("p");
        // set class attribute for div
        increment_el.setAttribute("class", "increment-section");
        decrement_el.setAttribute("class", "decrement-section");
        // set function attribute for div
        increment_el.setAttribute("onclick", "incrementValue(this)");
        decrement_el.setAttribute("onclick", "decrementValue(this)");
        // add text for div
        increment_el.innerText = "+";
        decrement_el.innerText = "-";
        // ser attribute for input
        input_el.setAttribute("type", "number");
        input_el.setAttribute("value", "00");
        input_el.setAttribute("class", time);
        input_el.setAttribute("name", `${section_id}-${time}`);
        // set attribute for p
        p_el.setAttribute("class", "time-label");
        // add text for p
        if (time === "hour") {
            p_el.innerText = "HH";
        }else if (time === "minute") {
            p_el.innerText = "MM";
        }else {
            p_el.innerText = "SS";
        }
        // append 4 elements in time_el
        time_el.append(increment_el);
        time_el.append(input_el);
        time_el.append(decrement_el);
        time_el.append(p_el);
    }
}

If you don't understand much about this function and how it works. So let me know in the comments. I would be very happy to assist you.

calculate(): Calculates the total time based on the values entered in the input sections, then formats and displays the result.
// function for calculate the final result and show
function calculate () {
    const form_el = document.querySelector("form");
    const form_data = new FormData (form_el);
    
    let hour_list = [];
    let minute_list = [];
    let second_list = [];
    
    for (let data of form_data) {
        if (data[0].includes("hour")) {
            hour_list.push(parseInt(data[1]));
        }else if (data[0].includes("minute")) {
            minute_list.push(parseInt(data[1]));
        }else if (data[0].includes("second")) {
            second_list.push(parseInt(data[1]));
        }
    }
    
    const total_hours = sumArray(hour_list);
    const total_minutes = sumArray(minute_list);
    const total_seconds = sumArray(second_list);
    
    const result = organizeTime(total_hours, total_minutes, total_seconds);
    
    // get result element
    const result_el = document.getElementById("result");
    result_el.innerText = result;
}

4. Helper Functions:

sumArray(arr): Sums up all elements in an array.
// function for add all elements in a specific array. In this case (arr)
function sumArray(arr) {
    let sum_arr = 0;
    for (let i = 0; i < arr.length; i++) {
        sum_arr += arr[i];
    }
    return sum_arr;
}

For Example:
// Example
const hour_arr = [1, 2, 3];
const min_arr = [4, 5, 6];
const sec_arr = [7, 8, 9];

// function for add all elements in a specific array. In this case (arr)
function sumArray(arr) {
    let sum_arr = 0;
    for (let i = 0; i < arr.length; i++) {
        sum_arr += arr[i];
    }
    return sum_arr;
}

const total_hour = sumArray(hour_arr);
const total_min = sumArray(min_arr);
const total_sec = sumArray(sec_arr);

console.log(total_hour); // output 6 (1 + 2 + 3)
console.log(total_min); // output 15 (4 + 5 + 6)
console.log(total_sec); // output 24 (7 + 8 + 9)

organizeTime(total_hours, total_minutes, total_seconds): Formats the total time (in hours, minutes, and seconds) into a human-readable string format.
// function for format time and return as string
function organizeTime(total_hours, total_minutes, total_seconds) {
    // Calculate the total time in seconds
    let total_seconds_all = total_hours * 3600 + total_minutes * 60 + total_seconds;

    // Calculate hours, minutes, and seconds
    let hours = Math.floor(total_seconds_all / 3600);
    let remaining_seconds = total_seconds_all % 3600;
    let minutes = Math.floor(remaining_seconds / 60);
    let seconds = remaining_seconds % 60;

    // Format the hours, minutes, and seconds with leading zeros if necessary
    let formatted_hours = hours < 10 ? '0' + hours : hours;
    let formatted_minutes = minutes < 10 ? '0' + minutes : minutes;
    let formatted_seconds = seconds < 10 ? '0' + seconds : seconds;

    // Return the organized time as a string
    return `${formatted_hours}:${formatted_minutes}:${formatted_seconds}`;
}

For Example:
// Example
// please see previous example of sumArray(arr)
// to understand total_hour, total_min and total_sec
const total_hour = 6;
const total_min = 15;
const total_sec = 24;

const formatted_time = organizeTime(total_hour, total_min, total_sec);

console.log(formatted_time); // 06:15:24 (HH:MM:SS)


Great job on completing your tutorial! You've learned how to create a web application that efficiently calculates time, streamlining your daily tasks. By following along with the step-by-step guide and exploring the JavaScript code, you've gained valuable insights into web development and JavaScript programming.

Remember, practice makes perfect, so keep experimenting with your newfound knowledge to build even more exciting projects. Stay tuned for future updates and more tutorials as we continue to explore the fascinating world of web development together.

Your Feedback Matters

Your feedback is essential to me. If you found any part of this tutorial challenging to understand or if you have suggestions for improvement, please don't hesitate to share. I value your input, and I'm committed to making this tutorial as clear and helpful as possible for everyone.

Together, we can create a better learning experience.


Thank you for joining me on this journey, and happy coding!




Comments

Popular posts from this blog

Creating a Dynamic Progress Bar with HTML, CSS, and JavaScript

A Step by Step Guide Introduction: In this tutorial, we'll walk through the process of building a dynamic progress bar using HTML, CSS, and JavaScript. Progress bars are commonly used in web applications to visualize the completion status of a task or process. By the end of this tutorial, you'll have a functional progress bar that updates in real-time based on user input. Figure: Preview (tap to see clearly) Prerequisites: Before diving into this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Familiarity with concepts such as HTML elements, CSS styling, and JavaScript functions will be beneficial. Step-by-Step Guide: Setting up the HTML structure Styling the progress bar with CSS Adding interactivity with JavaScript 1. Setting up the HTML structure Code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...