-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
70 lines (40 loc) · 2.14 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(function () {
"use strict";
let convertType = 'Miles';
const heading = document.querySelector("h1");
const intro = document.querySelector("p");
const answerDiv = document.getElementById('answer');
const form = document.getElementById('convert');
document.addEventListener('keydown', function(event){
var key = event.code;
if( key === 'KeyK'){
convertType='Kilometers'; //change the value of the convertType variable
heading.innerHTML='Kilometers to Miles Converter'; //change the heading
intro.innerHTML = 'Type in a number of kilometers and click the button to convert the distance to miles'; //change the intro paragraph
}
else if(key === 'KeyM'){
convertType='Miles'; //change the value of the convertType variable
heading.innerHTML='Miles to Kilometers Converter'; //change the heading
intro.innerHTML = 'Type in a number of miles and click the button to convert the distance to kilometers'; //change the intro paragraph
}
});
form.addEventListener('submit', function(event){
event.preventDefault();
const distance = parseFloat(document.getElementById("distance").value);
if (distance){
// convert M to K 1.609344
// convert K to M 0.621371192
if (convertType =='Miles'){
const conversion = (distance * 1.609344).toFixed(3); //toFixed will round the answer to 2 decimal points
answerDiv.innerHTML = `<h2>${distance} miles converts to ${conversion} kilometers </h2>`;
}
else {
const conversion = (distance * 0.621371192).toFixed(3); //toFixed will round the answer to 2 decimal points
answerDiv.innerHTML = `<h2>${distance} kilometers converts to ${conversion} miles </h2>`;
}
}
else {
answerDiv.innerHTML = `<h2> Please enter a number! </h2>`;
}
});
})();