How to create a simple web application that converts or calculator miles to kilometers using JavaScript, CSS and HTML, you can follow the steps below. This example includes an HTML form for user input, JavaScript for the conversion logic, and a display area to show the result.
Code Example: Miles to Kilometers Converter
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Miles to Kilometers Converter</title> <style> body { font-family: Arial, sans-serif; margin: 50px; } .container { max-width: 300px; 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 Kilometers Converter</h1> <input type="number" id="milesInput" placeholder="Enter miles" step="0.01"> <button onclick="convertMilesToKm()">Convert</button> <div class="result" id="result"></div> </div> <script> function convertMilesToKm() { // Get the input value in miles const miles = parseFloat(document.getElementById("milesInput").value); // Check if the input is a valid number if (isNaN(miles)) { document.getElementById("result").innerText = "Please enter a valid number!"; return; } // Conversion factor: 1 mile = 1.60934 kilometers const kilometers = miles * 1.60934; // Display the result document.getElementById("result").innerText = `${miles} miles = ${kilometers.toFixed(2)} kilometers`; } </script> </body> </html>
How It Works?
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.
JavaScript Logic:
-> The convertMilesToKm() function is called when the button is clicked.
-> It retrieves the input value using document.getElementById(“milesInput”).value.
-> Converts the input from miles to kilometers using the formula: kilometers = miles * 1.60934.
-> Displays the result in the result div.
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 (e.g., 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 kilometers.
Example Output:
If the user enters 10 miles, the output will be:
10 miles = 16.09 kilometers
This simple application demonstrates how to use HTML, CSS, and JavaScript to create an interactive miles-to-kilometers converter. You can expand this by adding more features, such as converting kilometers back to miles or improving the UI.