Javascript Calculator 1

Javascript Calculator

let screen = document.getElementById('screen');
buttons = document.querySelectorAll('button');
let screenValue = '';
for (item of buttons) {
    item.addEventListener('click', (e) => {
        buttonText = e.target.innerText;
        console.log('Button text is ', buttonText);
        if (buttonText == 'X') {
            buttonText = '*';
            screenValue += buttonText;
            screen.value = screenValue;
        }
        else if (buttonText == 'C') {
            screenValue = "";
            screen.value = screenValue;
        }
        else if (buttonText == '=') {
            screen.value = eval(screenValue);
        }
        else {
            screenValue += buttonText;
            screen.value = screenValue;
        }

    })
}

Here is what the above code is Doing:
1. We are selecting the screen element and storing it in a variable called screen.
2. We are selecting all the buttons and storing them in a variable called buttons.
3. We are creating a variable called screenValue and assigning it an empty string.
4. We are looping through all the buttons and attaching an event listener to each of them.
5. When a button is clicked, we are getting the text of the button and storing it in a variable called buttonText.
6. If the buttonText is ‘X’, we are replacing it with ‘*’ and adding it to the screenValue.
7. If the buttonText is ‘C’, we are clearing the screenValue.
8. If the buttonText is ‘=’, we are evaluating the screenValue and displaying the result on the screen.
9. If the buttonText is anything else, we are adding it to the screenValue.

Similar Posts