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

tips calculator page

michaellosdevβ€’ 20

@michaellosdev

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


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

P
Alexβ€’ 1,990

@AlexKMarshall

Posted

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 parameter

You 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 the data-tip-percent from the element using getAttribute. 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
Isabela Oliveiraβ€’ 310

@oliverids

Posted

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 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