Advertisement
bAngelov

Distance Converter

Mar 28th, 2024 (edited)
583
0
38 min
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEventsListeners() {
  2.  
  3.     const [fromElement,toElement] = document.querySelectorAll("body > div select")
  4.     document.getElementsByTagName("body")[0].addEventListener("click",handleConversion)
  5.  
  6.     const unitsInMeters = {
  7.         km: 1000,
  8.         m: 1,
  9.         cm: 0.01,
  10.         mm: 0.001,
  11.         mi: 1609.34,
  12.         yrd: 0.9144,
  13.         ft: 0.3048,
  14.         in: 0.0254,
  15.     }
  16.  
  17.     const unitToMeter = (unit,value) => Number(value) * unitsInMeters[unit]
  18.     const unitFromMeter = (unit,value) => Number(value) / unitsInMeters[unit]
  19.  
  20.     function handleConversion(event){
  21.         if(event.target.type !== "button") return
  22.  
  23.         // following lines won't work in judge
  24.         //const from = fromElement.querySelector("option:checked").value
  25.         //const to = toElement.querySelector("option:checked").value
  26.  
  27.         //simply getting select element's value instead
  28.         const from = fromElement.value
  29.         const to = toElement.value
  30.  
  31.         const fromInput = fromElement.previousElementSibling.value
  32.         const toField = toElement.previousElementSibling
  33.         if(!unitsInMeters[from] || !unitsInMeters[to]) return
  34.         const result = unitFromMeter(to,unitToMeter(from,fromInput))
  35.         toField.removeAttribute("disabled")
  36.         toField.value = result
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement