Browse Source

lil' minimization of code

miskson 2 years ago
parent
commit
272d299697
1 changed files with 11 additions and 8 deletions
  1. 11 8
      hw1/script.js

+ 11 - 8
hw1/script.js

@@ -49,6 +49,10 @@ const texts = [
     }
 ]
 
+
+const container = document.querySelector('.container')
+const reader = document.querySelector('.reader__wrapper')
+
 let currentSlide = 0
 
 function truncateFraction (number) {
@@ -78,15 +82,14 @@ function invokeError(bool, element, dependent) {
                 element.getElementsByTagName('small')[0].remove()
             }
             dependent.setAttribute('disabled', true)
-            dependent.closest('div').setAttribute('style', 'background-color: gold')
-            element.closest('div').setAttribute('style', 'background-color: red')
+            setBackgroundColor('gold', dependent.closest('div'))
+            setBackgroundColor('red', element.closest('div'))
             element.insertAdjacentHTML('beforeend', `
                 <small>Invalid value given</small>
             `)
         } else {
             dependent.removeAttribute('disabled')
-            dependent.closest('div').setAttribute('style', 'background-color: transparent')
-            element.closest('div').setAttribute('style', 'background-color: transparent')
+            setBackgroundColor('transparent', dependent.closest('div'), element.closest('div'))
             element.getElementsByTagName('small')[0].remove()
             element.style.backgoundColor = transparent;
         }
@@ -95,8 +98,9 @@ function invokeError(bool, element, dependent) {
     }
 }
 
-const container = document.querySelector('.container')
-const reader = document.querySelector('.reader__wrapper')
+function setBackgroundColor (color, ...elements) {
+    elements.forEach(element => element.setAttribute('style', `background-color: ${color}`))
+}
 
 container.addEventListener('input', (e) => {
     invokeError(isValidInput(e.target.value), e.target.closest('div'), document.getElementById(ratios[`${e.target.id}`].transition))
@@ -127,7 +131,6 @@ reader.addEventListener('click', (e) => {
     reader.getElementsByTagName('article')[0].insertAdjacentHTML('beforeend', `
         <p><strong>Tip:</strong> ${texts[currentSlide].tip}</p>
     `)
-    reader.getElementsByTagName('strong')[0].style.backgroundColor = 'gold';
+    setBackgroundColor('gold', reader.getElementsByTagName('strong')[0])
     reader.getElementsByTagName('strong')[0].style.color = 'black';
 })
-