How to Build a Unit Converter for Your Baking Needs with HTML, CSS & Vanilla JavaScript
If you've ever found yourself in the midst of a baking project, only to realize that your recipe uses measurements in cups, while your kitchen is stocked with teaspoons and tablespoons, you're not alone.
Baking can be a precise science, and having the right unit conversions at your fingertips can make all the difference in the outcome of your delicious creations.
In this blog post, we'll show you how to build a unit converter with HTML, CSS, and Vanilla JavaScript that's tailored to your baking needs. Whether you're converting from cups to teaspoons, tablespoons, or even handling temperature conversions, this simple yet powerful feature will become an invaluable tool in your kitchen. Say goodbye to kitchen confusion and hello to perfect pastries, cakes, and cookies! Let's get started on your journey to developing this simple yet useful feature.
Create a Basic HTML Form Structure
In this section, we are setting up the basic HTML structure for our unit converter, which will be a valuable tool for your baking needs. This HTML form includes various input fields for converting measurements, making your baking experience more convenient and accurate. The form features fields for quantity conversions, such as cups, tablespoons, teaspoons, ounces, grams, and milliliters, along with temperature conversions between degrees Celsius and degrees Fahrenheit.
<!-- weight convertor modal box starts -->
<form action="" class="convertor-form">
<h3>
<i class="fas fa-spoon"></i> Unit Convertor
<i class="fas fa-times" id="close-convertor"></i>
</h3>
<p>Quantity:</p>
<article class="input-wrapper">
<label for="cups">cups: </label>
<input type="number" id="cups" value="1" />
</article>
<article class="input-wrapper">
<label for="tbsp">tablespoon (tbsp): </label>
<input type="number" id="tbsp" />
</article>
<article class="input-wrapper">
<label for="tsp">teaspoon (tsp): </label>
<input type="number" id="tsp" />
</article>
<article class="input-wrapper">
<label for="oz">ounces (oz): </label>
<input type="number" id="oz" />
</article>
<article class="input-wrapper">
<label for="gms">grams (gms): </label>
<input type="number" id="gms" />
</article>
<article class="input-wrapper">
<label for="ml">milliliters (ml): </label>
<input type="number" id="ml" />
</article>
<p>Temperature:</p>
<article class="input-wrapper">
<label for="degC">deg celsius (deg C): </label>
<input type="number" id="degC" value="1" />
</article>
<article class="input-wrapper">
<label for="degF">deg fahrenheit (deg F):</label>
<input type="number" id="degF" />
</article>
</form>
<!-- weight convertor modal box ends -->
The above code is an HTML structure that defines a "weight converter modal box" within a bakery’s web page. It's intended for a baking-related project and is part of a user interface where users can convert between different units of measurement for both quantity (e.g., cups, tablespoons, teaspoons, ounces, grams, milliliters) and temperature (e.g., degrees Celsius and degrees Fahrenheit).
Here's a breakdown of the elements in this HTML code:
<form>
: This element defines a form, which is typically used to collect user input. In this case, it is used for inputting values to convert.class="convertor-form"
: This class attribute assigns the "convertor-form" class to the form, which will be used for styling and scripting purposes.<h3>
: This is a heading element, and it contains the title "Unit Convertor." It also includes two icons, which are represented using the Font Awesome classes "fas fa-spoon" and "fas fa-times." These icons will serve as visual elements for the unit converter as indicator and closing the modal is it’s a part of a bigger project.<p>
: These are paragraphs used to label the sections of the form. The first one says "Quantity," and the second one says "Temperature."<article class="input-wrapper">
: These elements define sections within the form where input fields are placed. The class "input-wrapper" will be used for styling purposes.<label>
: Labels are used to describe the purpose of the associated input fields. For example, "cups," "tablespoon (tbsp)," "teaspoon (tsp)," and so on.<input>
: These are input fields where users can enter numeric values. They have various types (e.g., "number") and unique IDs (e.g., "cups," "tbsp") that can be used to reference and manipulate them through JavaScript.
Now, we’ll add some CSS styling to make our form look interesting. Since this mini-project is part of a bigger bakery website project, you’ll find some standard styles and root variables which are optional to implement.
Sprinkle Some CSS Styling to the Form
In the next phase of our project, we will be adding stylish flair to our unit conversion form. Styling is not only about aesthetics but also plays a crucial role in enhancing the user experience. We'll use CSS to apply colors, layout, and design elements that make our form visually appealing and user-friendly. With a well-crafted design, our unit converter will not only be a practical tool for your baking needs but also a delight to interact with. Get ready to transform your plain form into an attractive and functional piece of web design in this section.
/* Common Styles File for all HTML files index, about, shop, and cart */
/* font import from google fonts */
@import url("<https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300;400;500;600;700&display=swap>");
/* Root style variables for the complete document for reduction in code repetition */
:root {
--rubyRed: #9b2226;
--rufous: #ae2012;
--rust: #bb3e03;
--alloyOrange: #ca6702;
--gamboge: #ee9b00;
--mediumChampagne: #e9d8a6;
--middleBlueGreen: #94d2bd;
--viridianGreen: #0a9396;
--blueSapphire: #005f73;
--richBlack: #001219;
--antiquewhite: #fff1c9;
--box-shadow: 0 0.5rem 1.5rem rgba(0, 18, 25, 0.1);
--border: var(--rufous) 0.15rem solid;
--border-small: var(--rufous) 0.05rem solid;
--outline: 0.1rem solid rgba(0, 18, 25, 0.1);
--outline-hover: 0.2rem solid var(--richBlack);
}
/* Standard root styles for the full body of html documents to reset box sizing and fonts */
* {
font-family: "Signika Negative", sans-serif;
margin: 0;
box-sizing: border-box;
outline: 0;
border: none;
text-decoration: none;
text-transform: capitalize;
transition: all 0.2s linear;
}
/* remove scroll in x-direction, set scroll behavior and set scroll padding to avoid clash of header bar and content */
html {
overflow-x: hidden;
scroll-behavior: smooth;
scroll-padding-top: 7rem;
}
/* set background color of body */
body {
background: var(--mediumChampagne);
overflow-x: hidden;
}
/* user unit convertor box style starts */
.header .convertor-form {
position: absolute;
top: 110%;
/* right: 1.2rem; */
width: 90%;
box-shadow: var(--box-shadow);
border: var(--border);
padding: 1.2rem;
border-radius: 0.5rem;
background-color: var(--antiquewhite);
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
}
.header .convertor-form h3 {
font-size: 2rem;
color: var(--blueSapphire);
text-align: center;
}
.header .convertor-form .input-wrapper {
padding: 0.6rem 0;
width: min-content;
}
.header .convertor-form input {
background-color: #fff;
border-radius: 0.5rem;
font-size: 1.5rem;
color: var(--black);
text-transform: none;
border: var(--border-small);
box-shadow: var(--box-shadow);
text-align: center;
height: 3rem;
}
.header .convertor-form p {
font-size: 1.2rem;
font-weight: 500;
margin: 0.5rem auto 0 auto;
}
.header .convertor-form label {
font-size: 1.2rem;
padding: 0.4rem 0;
color: var(--richBlack);
text-align: center;
}
#close-convertor {
font-size: 1.8rem;
color: var(--rubyRed);
padding: 0.5rem;
}
#close-convertor:hover {
color: var(--blueSapphire);
}
#close-convertor:active {
color: var(--blueSapphire);
}
/* unit convertor form box style ends */
This code snippet is a CSS (Cascading Style Sheets) file that contains a set of styles used for various HTML documents, including an "index," "about," "shop," and "cart." It defines common styles that will be applied consistently across these web pages. Here's a breakdown of the key elements and their purposes:
- Font Import:
@import url("<https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300;400;500;600;700&display=swap>");
: This imports the "Signika Negative" font family from Google Fonts, making it available for use in the web pages.
- Root Style Variables:
:root
: This defines CSS variables for the entire document. These variables are used to store color values, box shadows, border styles, and other properties that can be reused throughout the stylesheet. This approach reduces code repetition and makes it easier to maintain consistent styling.
- Standard Root Styles:
-
- : This sets a set of common styles that apply to all HTML elements. It removes margins, sets the box-sizing to border-box (which includes padding and border in the element's total width and height), removes borders, outlines, text decoration, and transforms text to capitalize. It also adds a smooth transition effect for all properties.
-
- HTML and Body Styles:
html
: This removes horizontal scrolling, sets smooth scrolling behavior, and provides scroll padding to avoid content overlapping with the header bar.body
: This sets the background color for the entire web page.
- Unit Converter Box Styles:
.header .convertor-form
: These styles are specific to a unit converter box located within an HTML element with the class "header." It defines the positioning, box shadow, border, padding, and other visual properties of the converter form..header .convertor-form h3
: Styles the heading inside the converter form..header .convertor-form .input-wrapper
: Styles the input wrappers within the form..header .convertor-form input
: Styles the input fields..header .convertor-form p
: Styles paragraphs within the form..header .convertor-form label
: Styles labels within the form.#close-convertor
: Styles a close button element with the ID "close-convertor." It defines its appearance and hover/active states.
These styles are organized and designed to maintain a consistent and visually appealing look and feel across multiple web pages, especially focusing on the unit converter box within the header section. The use of CSS variables and clear class and ID selectors helps to keep the code modular and maintainable.
Add Vanilla JavaScript to Make it Work
Welcome to the next exciting phase of our unit conversion project! In this section, we're about to bring your unit converter to life by adding Vanilla JavaScript magic. We'll dive into the DOM (Document Object Model) to grab the necessary elements, create functions for seamless unit conversion, and add event listeners to ensure a dynamic and interactive user experience. With these JavaScript additions, you'll be able to effortlessly input values, watch them convert in real-time, and have a powerful baking tool at your fingertips. Let's get ready to unleash the full potential of your unit converter!
Grab the Elements from the DOM
// script for weight and baking temperature conversion feature for baking purposes - feature is in navigation menu
// 1. got input elements
let gmsRef = document.getElementById("gms");
let ozRef = document.getElementById("oz");
let tspRef = document.getElementById("tsp");
let tbspRef = document.getElementById("tbsp");
let cupRef = document.getElementById("cups");
let mlRef = document.getElementById("ml");
let degCRef = document.getElementById("degC");
let degFRef = document.getElementById("degF");
This JavaScript code is the starting point for a weight and baking temperature conversion feature, specifically designed for baking purposes. It begins by selecting and storing references to various HTML input elements. Here's a breakdown of what each part of the code does:
- Selection of Input Elements:
let gmsRef = document.getElementById("gms");
: This line selects an HTML element with the ID "gms" and stores a reference to it in the variablegmsRef
.let ozRef = document.getElementById("oz");
: It does the same for an element with the ID "oz," storing it inozRef
.let tspRef = document.getElementById("tsp");
: This line selects the element with the ID "tsp" and stores a reference intspRef
.let tbspRef = document.getElementById("tbsp");
: Similarly, it selects the element with the ID "tbsp" and stores it intbspRef
.let cupRef = document.getElementById("cups");
: This line selects the element with the ID "cups" and stores it incupRef
.let mlRef = document.getElementById("ml");
: It selects the element with the ID "ml" and stores it inmlRef
.
- Temperature Conversion Elements:
let degCRef = document.getElementById("degC");
: This line selects an element with the ID "degC" and stores a reference to it in the variabledegCRef
.let degFRef = document.getElementById("degF");
: Similarly, it selects the element with the ID "degF" and stores it indegFRef
.
These variables, such as gmsRef
, ozRef
, and others, now hold references to the HTML input elements in your document. You can use these references to access and manipulate the values entered by users, perform unit conversions, and update the displayed results in your JavaScript code. This is a crucial step in making the conversion feature interactive and functional.
Create Functions to Handle the Unit Conversion
// 2. create function to convert from one unit to other values
let convertFromGrams = () => {
let gms = gmsRef.value;
// using toFixed method to limit decimals to 2 digits only
ozRef.value = (gms * 0.035274).toFixed(2);
tbspRef.value = (gms / 17.07).toFixed(2);
tspRef.value = (gms / 5.69).toFixed(2);
cupRef.value = (gms / 200).toFixed(2);
mlRef.value = (gms * 1).toFixed(1);
};
let convertFromOz = () => {
let oz = ozRef.value;
gmsRef.value = (oz * 28.3495).toFixed(2);
cupRef.value = (oz / 8).toFixed(2);
tbspRef.value = (oz * 2).toFixed(1);
tspRef.value = (oz * 6).toFixed(1);
mlRef.value = (oz * 30).toFixed(1);
};
let convertFromTbsp = () => {
let tbsp = tbspRef.value;
tspRef.value = (tbsp * 3).toFixed(1);
gmsRef.value = (tbsp * 17.07).toFixed(2);
cupRef.value = (tbsp / 16).toFixed(1);
ozRef.value = (tbsp / 2).toFixed(2);
mlRef.value = (tbsp * 15).toFixed(1);
};
let convertFromTsp = () => {
let tsp = tspRef.value;
tbspRef.value = (tsp / 3).toFixed(1);
gmsRef.value = (tsp * 5.69).toFixed(2);
cupRef.value = (tsp / 48).toFixed(2);
ozRef.value = (tsp / 6).toFixed(2);
mlRef.value = (tsp * 5).toFixed(1);
};
let convertFromCups = () => {
let cups = cupRef.value;
tbspRef.value = (cups * 16).toFixed(1);
tspRef.value = (cups * 48).toFixed(1);
gmsRef.value = (cups * 200).toFixed(1);
ozRef.value = (cups * 8).toFixed(1);
mlRef.value = (cups * 240).toFixed(1);
};
let convertFromMl = () => {
let ml = mlRef.value;
cupRef.value = (ml / 240).toFixed(3);
tspRef.value = (ml / 5).toFixed(2);
tbspRef.value = (ml / 15).toFixed(2);
gmsRef.value = (ml * 1).toFixed(1);
ozRef.value = (ml / 30).toFixed(2);
};
// convert baking temperatures
let convertFromDegC = () => {
let degC = degCRef.value;
degFRef.value = (degC * (9 / 5) + 32).toFixed(1);
};
let convertFromDegF = () => {
let degF = degFRef.value;
degCRef.value = ((degF - 32) * (5 / 9)).toFixed(1);
};
This JavaScript code defines a series of functions to perform unit conversions between different weight and baking temperature units. Each function takes the user input from one unit and calculates and updates the equivalent values in other units. Here's a breakdown of the key functions:
- Weight Conversions:
convertFromGrams()
: This function converts from grams to ounces, tablespoons, teaspoons, cups, and milliliters. It uses appropriate conversion factors and limits the result to 2 decimal places.convertFromOz()
: Converts from ounces to grams, cups, tablespoons, teaspoons, and milliliters. It also limits the result to 2 decimal places.convertFromTbsp()
: Converts from tablespoons to teaspoons, grams, cups, ounces, and milliliters, with results rounded to appropriate decimal places.convertFromTsp()
: Converts from teaspoons to tablespoons, grams, cups, ounces, and milliliters, rounding the results to the right decimal places.convertFromCups()
: Converts from cups to tablespoons, teaspoons, grams, ounces, and milliliters. It rounds the results accordingly.convertFromMl()
: Converts from milliliters to cups, teaspoons, tablespoons, grams, ounces. The precision is maintained in the results.
- Temperature Conversions:
convertFromDegC()
: Converts from degrees Celsius to degrees Fahrenheit using the formula (°C * 9/5 + 32). The result is rounded to 1 decimal place.convertFromDegF()
: Converts from degrees Fahrenheit to degrees Celsius using the formula ((°F - 32) * 5/9). The result is also rounded to 1 decimal place.
These functions ensure that when users input a value in one unit, the corresponding values in other units are calculated and displayed in real-time. This interactivity is a valuable feature for a unit conversion tool, making it a practical and user-friendly baking aid.
Finally, Add Event Listeners to Inputs
// adding event listeners to all input values and adding load listener to window to begin converting from 1 cup as soon as window loads
gmsRef.addEventListener("input", convertFromGrams);
ozRef.addEventListener("input", convertFromOz);
cupRef.addEventListener("input", convertFromCups);
tbspRef.addEventListener("input", convertFromTbsp);
tspRef.addEventListener("input", convertFromTsp);
mlRef.addEventListener("input", convertFromMl);
degCRef.addEventListener("input", convertFromDegC);
degFRef.addEventListener("input", convertFromDegF);
window.addEventListener("load", convertFromCups);
window.addEventListener("load", convertFromDegC);
// end of script for conversion feature for baking purposes
In this JavaScript code, event listeners are added to the input elements for both weight and temperature conversions. Additionally, a load
event listener is attached to the window to initiate conversions as soon as the page loads. Here's a breakdown of the code:
- Event Listeners for Weight Conversions:
gmsRef.addEventListener("input", convertFromGrams);
: This event listener listens for input changes in the "grams" input field and calls theconvertFromGrams
function to perform the conversion when the user enters a value.ozRef.addEventListener("input", convertFromOz);
: It listens for input changes in the "ounces" input field and calls theconvertFromOz
function to update other unit values accordingly.cupRef.addEventListener("input", convertFromCups);
: This event listener detects changes in the "cups" input field and triggers theconvertFromCups
function to calculate and update the other unit values.tbspRef.addEventListener("input", convertFromTbsp);
: It listens for input changes in the "tablespoons" input field and calls theconvertFromTbsp
function to perform the conversion.tspRef.addEventListener("input", convertFromTsp);
: This event listener is for the "teaspoons" input field, and it triggers theconvertFromTsp
function when the input value changes.mlRef.addEventListener("input", convertFromMl);
: Listens for input changes in the "milliliters" input field and calls theconvertFromMl
function to update other unit values accordingly.
- Event Listeners for Temperature Conversions:
degCRef.addEventListener("input", convertFromDegC);
: This event listener detects changes in the "degrees Celsius" input field and calls theconvertFromDegC
function to convert and display the temperature in degrees Fahrenheit.degFRef.addEventListener("input", convertFromDegF);
: It listens for changes in the "degrees Fahrenheit" input field and triggers theconvertFromDegF
function to display the temperature in degrees Celsius.
- Window Load Event Listeners:
window.addEventListener("load", convertFromCups);
: This event listener is triggered when the window (the page) is fully loaded. It initiates theconvertFromCups
function, which is responsible for the initial conversion from 1 cup to other units.window.addEventListener("load", convertFromDegC);
: Similarly, this event listener is used to initiate the temperature conversion from degrees Celsius to degrees Fahrenheit when the page is fully loaded.
These event listeners ensure that conversions are performed and updated in real-time as users input values, making the unit conversion feature for baking purposes interactive and responsive. The initial conversion from 1 cup and degrees Celsius upon page load provides users with immediate results.
Conclusion
In conclusion, we've embarked on a delightful journey of creating a unit converter tailored to your baking needs. This simple yet powerful feature is designed to make your baking projects a breeze, ensuring precision in your recipes. By combining HTML, CSS, and Vanilla JavaScript, we've transformed a basic form into a dynamic tool that effortlessly converts between various units of weight and temperature. Whether you're switching from cups to teaspoons, tablespoons, or dealing with temperature conversions, our interactive converter is here to save the day.
The addition of event listeners and real-time updates guarantees a seamless user experience, allowing you to focus on your baking without the hassle of manual calculations. With this tool in your baking arsenal, kitchen confusion becomes a thing of the past, making way for perfect pastries, cakes, and cookies.
So, say goodbye to measurement mishaps, and hello to stress-free baking. We hope you've enjoyed this journey and that your newfound baking companion serves you well. Happy baking and coding!