Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found

Submitted

Tip calculator using plain HTML/CSS/JS

#accessibility#bem
Ambreā€¢ 170

@Yunie08

Desktop design screenshot for the Tip calculator app coding challenge

This is a solution for...

  • HTML
  • CSS
  • JS
2junior
View challenge

Design comparison


SolutionDesign

Solution retrospective


Hi everyone ! Javascript is still very new to me so I'm sure my code is not optimized.

Do you know any "easy" way to add two event listeners to the same elements and with the same handler without repeating the code twice (example in my script.js : lines 99 to 147) ?

Any comment or advice is welcome :) Thanks and happy coding!

Community feedback

Adarshā€¢ 1,560

@adram3l3ch

Posted

function updateDOM (){
    
        let billValue = billInput.value;
        let tipValue = document.querySelector('input[name="tip"]:checked').value;
        let numberOfPeople = peopleInput.value;

        let resultTip = calculateTip(billValue, tipValue, numberOfPeople);
        let resultTotal = calculateTotal(billValue, tipValue, numberOfPeople);

        resultTipElt.innerText = `${resultTip}`;
        resultTotalElt.innerText = `${resultTotal}`;
}

function inputHandler (e){
      e.stopPropagation;
      if (resetButton.getAttribute('disabled') != null) {
        resetButton.removeAttribute('disabled');
      }
      let inputIsEmpty = inputsEmpty();
      if ((inputIsEmpty == true)) {
        console.log('input empty');
        resetButton.setAttribute('disabled',"");
      }
      let inputIsValid = checkInputs();
      if (inputIsValid == true) {
           updateDOM()
      }
}

function clickHandler (e){
      e.stopPropagation;
      let inputIsValid = checkInputs();
      if (inputIsValid == true) {
           updateDOM()
      }
}

document
  .querySelectorAll("input")
  .forEach(element => {
    element.addEventListener('input',inputHandler )
    element.addEventListener('click',clickHandler )
});

You can convert the repeating code to functions

Marked as helpful

0

Ambreā€¢ 170

@Yunie08

Posted

@adram3l3ch Thank you so much! I don't know why I find it very difficult to organize my javascript code clean and dry. You input helps a lot !

1

Please log in to post a comment

Log in with GitHub
Discord logo

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord