DEV Community

Brittany
Brittany

Posted on

Day 92 : #100DaysofCode - Created a JS Tip Calculator in JS

Check it out on my Github repo :)

tip-calculator-js

Logo

This Github Repo is a simple tip calculator that I created using HTML, CSS, Bootstrap, and Javascript as practice.




Below are a few things that I learned while building this calculator:

e.preventDefault()

I learned, the importance of e.preventDefault() when you are in development and using javascript.

While building my calculator, I would input a number and the page would immediately refresh. I could not figure out why until I reviewed some of the notes I took in the past about e.preventDefault()

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

How I interpret the above is that JS has default settings for event listeners and e.preventDefault() stops the default settings from from taken place unless it is called upon. I could be wrong, but all I know is that it stopped my page from constantly refreshing when I needed to handle my click event.

Changing Inputted Value from String to Integer

I also learned an easy way to convert a string to an integer:

    let checkAmount = document.getElementById('check-amount').value;
Enter fullscreen mode Exit fullscreen mode

Above document.getElementById('check-amount').value returns a string value that the user inputs. However, I was building a tip calculator meaning I had to make calculations and I can not do that with a string. So to convert the value, I learned that all I had to do was put a + in front of the value and it would convert it for me.

    let checkAmount = +document.getElementById('check-amount').value;
Enter fullscreen mode Exit fullscreen mode

isNaN function

Lastly, error catch! I learned how to use isNaN function to stop check if a value is NaN or not.

    if (isNaN(checkAmount)){
        displayResults("Error, please enter a number");
        return;
    }
Enter fullscreen mode Exit fullscreen mode

Song of the day: I have always been obsessed with brasstracks! Give them a listen 💕

Sincerely,
Brittany

Top comments (2)

Collapse
 
scroung720 profile image
scroung720 • Edited

Super inspiring series, thanks for sharing. It is better if you use Number.isNaN() instead of isNaN() otherwise there are cases where could be type coercion that throws an unexpected value.

Collapse
 
sincerelybrittany profile image
Brittany

This put a smile on my face! Thank you for reading 🙂💕