How to create a simple web application that converts miles to centimeters using JavaScript, CSS and HTML, you can follow the steps below. This will include an input field for miles, a button to trigger the conversion, and a display area for the result in centimeters.
Code Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Miles to Centimeters Converter</title> <style> body { font-family: Arial, sans-serif; margin: 50px; } .container { max-width: 400px; margin: 0 auto; text-align: center; } input[type="number"] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; } button { padding: 10px 20px; background-color: #007BFF; color: white; border: none; cursor: pointer; } button:hover { background-color: #0056b3; } .result { margin-top: 20px; font-size: 1.2em; } </style> </head> <body> <div class="container"> <h1>Miles to Centimeters Converter</h1> <label for="miles">Enter Miles:</label> <input type="number" id="miles" placeholder="Enter miles"> <button onclick="convertMilesToCm()">Convert</button> <div class="result" id="result"></div> </div> <script> function convertMilesToCm() { // Get the input value in miles const miles = parseFloat(document.getElementById("miles").value); // Check if the input is valid if (isNaN(miles)) { document.getElementById("result").innerText = "Please enter a valid number!"; return; } // Conversion factor: 1 mile = 160934.4 centimeters const centimeters = miles * 160934.4; // Display the result document.getElementById("result").innerText = `${miles} miles = ${centimeters.toFixed(2)} cm`; } </script> </body> </html>
How It Works?
1. HTML Structure:
– An input field (`<input type=”number”>`) allows the user to enter the number of miles.
– A button (`<button>`) triggers the conversion when clicked.
– A `<div>` with the ID `result` displays the converted value in centimeters.
2. JavaScript Logic:
– The `convertMilesToCm()` function is called when the button is clicked.
– It retrieves the input value in miles, converts it to centimeters using the conversion factor (`1 mile = 160934.4 cm`), and displays the result.
3. Styling:
– Basic CSS is used to style the input, button, and result display.
Steps to Run the Code:
1. Copy the code above into a file and save it as `index.html`.
2. Open the file in a web browser.
3. Enter a value in miles and click the “Convert” button to see the result in centimeters.
Example Output:
If you enter `1` mile, the result will be:
1 miles = 160934.40 cm
This simple tool is a great way to practice basic HTML, CSS, and JavaScript while creating a functional unit converter.