Hello, I created a simple interactive calculator with just 20 lines of Javascript code and I will be sharing it with you in this post.
This code can be implemented in your Javascript beginners’ project, so in case you don’t have an idea of what to build after tons of tutorials on Javascript?
Why not try this out? In a few minutes, your calculator will be running perfectly.
First of all, I guess you must have designed your graphical user interface (buttons and screen) with HTML and CSS.
If so, yes! let’s begin;
In this project I made of use of the div tag as my screen and my buttons were styled and were made interactive with hover and media query for responsiveness.
Now, to the JS code:
let display = document.getElementById('screen');
Here, I created a variable ‘display’ and with use of DOM, I linked my div with its id ‘screen’; this is where my output is shown. After this,
function isclicked(value) {
if(display.innerText === 0) {
display.innerText = value;
} else {
display.innerText += value;
}
return display.innerText;
}
Above, I declared a function ’isclicked’ which is linked to all my operations and numbers button (except the equal-to button) with the onclick attribute.
The function takes in the value of the button as its parameter (string) and show the value of button on the screen when clicked.
let equals = document.getElementById('equalto');
const equalClicked = () =>{
if(display.innerText !== "") {
display.innerText = eval(display.innerText)
} else {
display.innerText = "";
}
}
Next, I created a variable ‘equals’ that is linked to my equal-to button via its id. The function then evaluates the text on the screen by the use of the ‘eval’ keyword.
const clearClicked =() => {
display.innerText = "";
}
Lastly, this function is linked to my CLEAR button, the screen is empty when the button is clicked
Wow! You made it! By now, your calculator should be working perfectly.
You may also want to check the full project HERE
Also, make sure you follow me here, on Codepen and Medium for more exciting projects.
Thank you for reading!
Top comments (0)