Design comparison
Solution retrospective
I would like the feesback on my javaScript. I know that its possibble to make the code shorter by putting my "if esle" in the function, but for some reason it wouldn't work
Community feedback
- @AlexKMarshallPosted about 3 years ago
You've got a lot of duplication in your event handlers where each one only changes by the tip percentage amount. You can extract that into a reusable function that takes the
tipPercent
as a parameterYou can then call that in your event handlers.
You could go a step further and add a
data-tip-percent
value to each of your<button>
elements in your html. That way, instead of having separate event handlers for each button, you can have one event handler for all buttons and read thedata-tip-percent
from the element usinggetAttribute
. You can then pass that to your function created in step one.Going further still I would break that re-usable function into multiple smaller functions separating out functions that calculate a value from functions that change a display on the screen. That separates the concerns and would make it easier to update both the UI and the calculations if requirements changed in future.
1 - @oliveridsPosted about 3 years ago
For the tips, for example, you can shorten the code by using if else with the help of an event listener on a list of all buttons. Your code would look a bit like this:
let buttons= document.querySelectorAll('.tip-select btn'); //this will create a nodeList
buttons.forEach(each => {
each.addEventListener('click', event => {
if(event.currentTarget == fivePercent) {
//
} else if(event.currentTarget == fivePercent) {
//
} ...
}); });
Also, adding the attribute "type=number" also shortens your code because it'll only allow the user to type numbers, and you won't need to do the verification "if(NaN ...)".
0
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