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
- @adram3l3chPosted almost 3 years ago
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 helpful0@Yunie08Posted almost 3 years ago@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 GitHubJoin 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