Design comparison
Solution retrospective
Hello my name is João Vitor and i have completed another frontend mentor challenge.🔗
- I'm having trouble checking the inputs, I'm repeating the code many times but I have no idea how to reduce the repetition, if you could send me tutorials that helped you I would be very grateful 😐
How can i improve and reduce unnecessary code? Leave your comment. 😁
Community feedback
- @atmahanaPosted about 1 year ago
Hi there.
To reduce the repetition I would suggest the following:
Iterate through all the tip selection
Create a same class so you you can select all of them using JavaScript
<input class="tip-percent" id="five" type="button" value="0.05"> // change tip value from using "%" to this <input class="tip-percent" id="ten" type="button" value="0.1"> // the rest of the tip selection input
const tipsPercent = document.querySelectorAll(".tip-percent"); tipsPercent.forEach((tip) => { const tipValue = tip.value; // get the tip value from the input tip.addEventListener('click', () => { // the calculation goes here // you can use the value dynamically here let calculate = (billInput * tipValue) }) })
If you want to further simplify you code you can implement encapsulations. You can find the topic on Google or YouTube. Hope this helps!
Marked as helpful0 - @WDWaleedPosted about 1 year ago
You could take this approach to read inputs:
Add an onchange event listener to the input fields which will read the value every time it changes. You can read about this event listener in the MDN web docs
Marked as helpful0
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