DEV Community

Cover image for You Can Count On Me
Meg
Meg

Posted on • Edited on

You Can Count On Me

Yesterday during class we were set a task to create a calculator.

It’s been about 2 years since I did anything with event listeners but I love logic, so I figured I’d enjoy working through it.

I created the buttons, elements, and was then distracted by some fun code that changed the color of the background with a click. Then after a good night’s sleep I was finally able to traverse through my saved clicks and calculate for two numbers and an operator. Yay!

My next issue was crafting logic to handle double digit or longer numbers. I solved this by traversing my saved clicks and creating a stoplight that either concated the additional numbers into one index or didn’t.

The next problem was multiple operators and thus multiple calculations. After my original result from the first three clicks (eg 8x8) I ended up then traversing by twos, starting one index after I ended (index 4) that way I could always look back and use the previous operator (index) with my current number.

I considered writing logic alerting for multiple operators at once, and although I did alert if first click was with an operator, I left the rest to sort themselves out - just like any normal calculator you’d sat on.

The brief asked for console logs of the numbers (and if you’d like to check the math, they’re still there) but I decided to update the welcome message innertext to the calculated total. It also includes a tada emoji for funsies.

All in all it was a fun challenge that pushed me to go farther in my use of JS and CSS.

If you'd like to use it here's the Replit:
https://replit.com/@Meg-Div/Calculator#calculator.js

Here's the code: https://github.com/Meg-Div/DigitalCraftsProjects/tree/main/calculator

Top comments (1)

Collapse
 
nathannosudo profile image
Nathan Orris

Event listeners...thats a name I have not heard in a long long time.