JavaScript - calculator

Revision:


Content

calculator - example 1 calculator - example 2 calculator - example 3 calculator - example 4


calculator - example 1

top
example: calculator
code:
                        <div class="wrapper">
                            <section class="screen">
                                <div class="previous" data-operand-previous></div>
                                <div class="current" data-operand-current></div>
                            </section>
                            <section class="calc-btn_row">
                                <div class="calc_btn_row">
                                    <button class="calc_btn double" data-all-clear>C</button>
                                    <button class="calc_btn" data-delete>←</button>
                                    <button class="calc_btn" data-operation>÷</button>
                                </div>
                                <div class="calc_btn_row">
                                    <button class="calc_btn" data-number>7</button>
                                    <button class="calc_btn" data-number>8</button>
                                    <button class="calc_btn" data-number>9</button>
                                    <button class="calc_btn" data-operation>×</button>
                                </div>
                                <div class="calc_btn_row">
                                    <button class="calc_btn" data-number>4</button>
                                    <button class="calc_btn" data-number>5</button>
                                    <button class="calc_btn" data-number>6</button>
                                    <button class="calc_btn" data-operation>-</button>
                                </div>
                                <div class="calc_btn_row">
                                    <button class="calc_btn" data-number>1</button>
                                    <button class="calc_btn" data-number>2</button>
                                    <button class="calc_btn" data-number>3</button>
                                    <button class="calc_btn" data-operation>+</button>
                                </div>
                                <div class="calc_btn_row">
                                    <button class="calc_btn" data-number>.</button>
                                    <button class="calc_btn double" data-number>0</button>
                                    <button class="calc_btn" data-equals>=</button>
                                </div>
                            </section>
                        </div>
                        <style>
                            .wrapper {max-width: 30vw; margin: 0 4vw; padding: 0 0; background-color: black; height:35vw;}
                            .screen { display: flex; flex-flow: column nowrap; background-color: darkgrey; min-height: 4vw; padding: 1vw;  font-size: 2.5vw; 
                                font-weight: bold; font-family: "Roboto", sans-serif; text-align: left;}
                            .screen .previous {font-size: 1.5vw; color: blue; word-wrap: break-word; word-break: break-all;}
                            .screen .current { font-size: 2.5vw;  color: darkgreen; word-wrap: break-word; word-break: break-all;}
                            .calc_btn_row { display: flex; align-content: stretch; justify-content: space-between; margin-bottom: 0.5%;}
                            .calc_btn {background-color: orangered; color: black; font-family: "Roboto", sans-serif; font-weight: bold; font-size: 2.5vw;
                            border: none; height: 5vw; flex-basis: 24.5%; cursor: pointer; margin-left:0.1vw; }
                            .calc_btn:hover { background-color: #af4646;}
                            .calc_btn:active { background-color: #bbbcbe;}
                            .calc_btn:last-child { background-color: burlywood; color: brown;}
                            .calc_btn:last-child:hover {background-color: lightgrey;}
                            .double { flex-basis: 49.7%; }
                        </style>
                        <script>
                            const numberButtons = document.querySelectorAll("[data-number]");
                            const operationButtons = document.querySelectorAll("[data-operation]");
                            const equalsButton = document.querySelector("[data-equals]");
                            const deleteButton = document.querySelector("[data-delete]");
                            const allClearButton = document.querySelector("[data-all-clear]");
                            const currentScreenTextElement = document.querySelector( "[data-operand-current]");
                            const previousScreenTextElement = document.querySelector("[data-operand-previous]");
                    
                            class Calculator {
                                constructor(currentScreenTextElement, previousScreenTextElement) {
                                    this.currentScreenTextElement = currentScreenTextElement;
                                    this.previousScreenTextElement = previousScreenTextElement;
                                    this.clear();
                                }
                                clear() {
                                    this.currentOperand = "";
                                    this.previousOperand = "";
                                    this.operation = null;
                                }
                                delete() {
                                    this.currentOperand = this.currentOperand.toString().slice(0, -1);
                                }
                                appendNumber(number) {
                                    if (number === "." && this.currentOperand.includes(".")) return;
                                    this.currentOperand = this.currentOperand.toString() + number.toString();
                                }
                                flushOperator(operation) {
                                    if (this.currentOperand === "") return;
                                    if (this.previousOperand !== "") {
                                        this.compute();
                                    }
                                    this.operation = operation;
                                    this.previousOperand = this.currentOperand;
                                    this.currentOperand = "";
                                }
                                compute() {
                                    let computation;
                                    const previous = parseFloat(this.previousOperand);
                                    const current = parseFloat(this.currentOperand);
                                    if (isNaN(previous) || isNaN(current)) return;
                                    switch (this.operation) {
                                    case "+":
                                        computation = previous + current;
                                        break;
                                case "-":
                                    computation = previous - current;
                                    break;
                                case "×":
                                    computation = previous * current;
                                    break;
                                case "÷":
                                    computation = previous / current;
                                    break;
                                default:
                                    return;
                                }
                                    this.currentOperand = computation;
                                    this.previousOperand = "";
                                    this.operation = undefined;
                                }
                    
                                updateDisplay() {
                                    this.currentScreenTextElement.innerText = this.currentOperand;
                                    if (this.operation != null) {
                                    this.previousScreenTextElement.innerText = `${this.previousOperand} ${this.operation}`;
                                    }
                                }
                            }
                            const calculator = new Calculator(currentScreenTextElement,  previousScreenTextElement );
                            numberButtons.forEach((button) => {
                                button.addEventListener("click", () => {
                                    calculator.appendNumber(button.innerText);
                                    calculator.updateDisplay();
                                });
                            });
                            operationButtons.forEach((button) => {
                                button.addEventListener("click", () => {
                                    calculator.flushOperator(button.innerText);
                                    calculator.updateDisplay();
                                });
                            });
                            equalsButton.addEventListener("click", () => {
                                calculator.compute();
                                calculator.updateDisplay();
                            });
                            allClearButton.addEventListener("click", () => {
                                calculator.clear();
                                calculator.updateDisplay();
                            });
                            deleteButton.addEventListener("click", () => {
                                calculator.delete();
                                calculator.updateDisplay();
                            });
                        </script>   
                            
                    


calculator - example 2

top
example: calculator










code:
                <div class="formstyle">
                    <form name = "form1">  
                    <!-- This input box shows the button pressed by the user in calculator. -->  
                    <input id = "calc" type ="text" name = "answer"> <br> <br>     
                    <!-- Display the calculator button on the screen. -->  
                    <!-- onclick() function display the number prsses by the user. -->  
                    <input type = "button" value = "1" onclick = "form1.answer.value += '1' ">  
                    <input type = "button" value = "2" onclick = "form1.answer.value += '2' ">  
                    <input type = "button" value = "3" onclick = "form1.answer.value += '3' ">  
                    <input type = "button" value = "+" onclick = "form1.answer.value += '+' ">  
                    <br> <br>   
                        
                    <input type = "button" value = "4" onclick = "form1.answer.value += '4' ">  
                    <input type = "button" value = "5" onclick = "form1.answer.value += '5' ">  
                    <input type = "button" value = "6" onclick = "form1.answer.value += '6' ">  
                    <input type = "button" value = "-" onclick = "form1.answer.value += '-' ">  
                    <br>  <br>   
                        
                    <input type = "button" value = "7" onclick = "form1.answer.value += '7' ">  
                    <input type = "button" value = "8" onclick = "form1.answer.value += '8' ">  
                    <input type = "button" value = "9" onclick = "form1.answer.value += '9' ">  
                    <input type = "button" value = "*" onclick = "form1.answer.value += '*' ">  
                    <br>  <br>   
                                
                    <input type = "button" value = "/" onclick = "form1.answer.value += '/' ">  
                    <input type = "button" value = "0" onclick = "form1.answer.value += '0' ">  
                        <input type = "button" value = "." onclick = "form1.answer.value += '.' ">  
                        <!-- When we click on the '=' button, the onclick() shows the sum results on the calculator screen. -->  
                    <input type = "button" value = "=" onclick = "form1.answer.value = eval(form1.answer.value) ">  
                    <br>   
                    <!-- Display the Cancel button and erase all data entered by the user. -->  
                    <input type = "button" value = "Clear All" onclick = "form1.answer.value = ' ' " id= "clear1" >  
                    <br>   
                        
                    </form>  
                </div> 
                <style>
                #clear1{width: 20vw; border: 0.2vw solid gray; border-radius: 0.3vw; padding: 0.5vw; background-color: orangered;cursor:pointer;}  
                .formstyle{width: 22vw; height: 36vw; margin: auto; border: 0.3vw outset dodgerblue; border-radius: 0.5vw; padding: 2vw;}  
                input {width: 4.25vw; background-color: burlywood;  
                    color: black; border: 0.3vw solid black; border-radius: .5vw; padding: 1.5vw; margin: 0.4vw; font-size: 1.5vw;}  
                #calc{width: 17.5vw; border: .5vw solid black; border-radius: .3vw; padding: 1vw; margin: auto;}  
                </style> 
            


calculator - example 3

top
example: calculator

                            
0
code:
                    <div class="container">
                        <div class="calculator-a">
                            <div class="output">
                                <pre id="upper"></pre>
                                <pre id="lower">0</pre>
                            </div>
                            <div class="input">
                                <button onclick="pressAllClear()">AC</button>
                                <button onclick="pressNum(this)">0</button>
                                <button onclick="pressClear()">Clear<i class="fas fa-backspace"></i></button>
                                <button onclick="pressOperator(this)">+</button>
                                <button onclick="pressNum(this)">1</button>
                                <button onclick="pressNum(this)">2</button>
                                <button onclick="pressNum(this)">3</button>
                                <button onclick="pressOperator(this)">-</button>
                                <button onclick="pressNum(this)">4</button>
                                <button onclick="pressNum(this)">5</button>
                                <button onclick="pressNum(this)">6</button>
                                <button onclick="pressOperator(this)">×</button>
                                <button onclick="pressNum(this)">7</button>
                                <button onclick="pressNum(this)">8</button>
                                <button onclick="pressNum(this)">9</button>
                                <button onclick="pressOperator(this)">÷</button>
                                <button onclick="pressDot()">.</button>
                                <button onclick="pressBracket(this)">(</button>
                                <button onclick="pressBracket(this)">)</button>
                                <button onclick="pressEqual()">=</button>
                            </div>
                        </div>
                    </div>
                    <style>
                    .container {display: flex; justify-content: center; align-items: center; height: 55vh; width: 30vw;background-color: #4e4e4e;}
                    .calculator-a {background: burlywood; border-radius: .5vw; padding: .5vw; width: 25vw;  min-width: 15vw; 
                        box-shadow: inset .2vw .2vw .5vw rgba(255, 255, 255, 0.4), .4vw .4vw 1vw rgba(0, 0, 0, 0.7);}
                    .output { display: flex; flex-direction: column; align-items: flex-end; position: relative; background: aliceblue; 
                        min-height: 3vw; padding: .3vw; margin: 0 .1vw 1vw; border-radius: 0.25vw; box-shadow: inset .1vw .1vw .5vw rgba(0, 0, 0, 0.5);}
                    .output pre {text-align: right; font-size: 1.5vw; margin: 0; font-family: 'Orbitron', sans-serif; width: 24vw; overflow-x: auto;
                    -ms-overflow-style: none; scrollbar-width: none;}
                    .output pre::-webkit-scrollbar {display: none;}
                    .output #upper {color: #424242; font-size: 1.8vw;}
                    .input {display: flex; flex-wrap: wrap; justify-content: space-between;}
                    .input button {width: calc(25% - 2vw); height: 2.5vw; margin: .4vw 0.8vw; border-radius: 50%; background-color: #c05d5d; 
                        box-shadow: inset .1vw .1vw .2vw rgba(255, 255, 255, 0.3), .1vw .1vw .5vw rgba(94, 31, 31, 0.7); color: white; 
                        font-size: 1vw; font-weight: bold; cursor: pointer; outline: none; border: none;}
                    .input button:hover {background-color: orangered;}
                    .input button:active {box-shadow: inset .1vw .1vw 1vw blue, inset -.1vw -.1vw .2vw rgba(255, 255, 255, 0.3); color: green; }
                    </style>
                    <script>
                        // upper output is for showing the expression
                        let outputUpper = document.querySelector('#upper');
                        // lower output is for showing the result
                        let outputLower = document.querySelector('#lower');
                        // function to get number input
                        function pressNum(e) {
                            if (outputLower.innerHTML === '0') {
                                outputLower.innerHTML = e.innerHTML;
                            } else {
                                outputLower.innerHTML += e.innerHTML;
                            }
                        }
                        // clear all
                        function pressAllClear() {
                            outputUpper.innerHTML = '';
                            outputLower.innerHTML = '0';
                        }
                        // clear one
                        function pressClear() {
                            outputLower.innerHTML = outputLower.innerHTML.slice(0, -1);
                        }
                        // calculate button
                        function pressEqual() {
                            let exp = outputLower.innerHTML;
                            outputUpper.innerHTML = exp;
                            exp = exp.replace(/×/g, '*').replace(/÷/g, '/');
                            let result;
                            try {
                                result = eval(exp);
                                // if decimal number more than 4 decimal places
                                if (result.toString().indexOf('.') !== -1) {
                                    result = result.toFixed(4);
                                }
                            } catch (e) {
                                result = 'Error';
                            }
                            outputLower.innerHTML = result;
                        }
            
                        function pressOperator(e) {
                            // check last operator
                            let lastOperator = outputLower.innerHTML.slice(-1);
                            if (lastOperator.includes('+', '-', '×', '÷')) {
                                    output.innerHTML = outputLower.innerHTML.slice(0, -1) + e.innerHTML;
                                } else {
                                    outputLower.innerHTML += e.innerHTML;
                                }
                            }
                            function pressDot() {
                                outputLower.innerHTML += '.';
                            }
                            function pressBracket(e) {
                                outputLower.innerHTML += e.innerHTML;
                            }
                            // attach keyboard event
                            document.addEventListener('keydown', function (e) {
                            switch (e.key) {
                                case '0':
                                pressNum(document.querySelector('button:nth-child(2)'));
                                break;
                                case '1':
                                pressNum(document.querySelector('button:nth-child(5)'));
                                break;
                                case '2':
                                pressNum(document.querySelector('button:nth-child(6)'));
                                break;
                                case '3':
                                pressNum(document.querySelector('button:nth-child(7)'));
                                break;
                                case '4':
                                pressNum(document.querySelector('button:nth-child(9)'));
                                break;
                                case '5':
                                pressNum(document.querySelector('button:nth-child(10)'));
                                break;
                                case '6':
                                pressNum(document.querySelector('button:nth-child(11)'));
                                break;
                                case '7':
                                pressNum(document.querySelector('button:nth-child(13)'));
                                break;
                                case '8':
                                pressNum(document.querySelector('button:nth-child(14)'));
                                break;
                                case '9':
                                pressNum(document.querySelector('button:nth-child(15)'));
                                break;
                                case '+':
                                pressOperator(document.querySelector('button:nth-child(4)'));
                                break;
                                case '-':
                                pressOperator(document.querySelector('button:nth-child(8)'));
                                break;
                                case '*':
                                pressOperator(document.querySelector('button:nth-child(12)'));
                                break;
                                case '/':
                                pressOperator(document.querySelector('button:nth-child(16)'));
                                break;
                                case '.':
                                pressDot();
                                break;
                                case '(':
                                pressBracket(document.querySelector('button:nth-child(18)'));
                                break;
                                case ')':
                                pressBracket(document.querySelector('button:nth-child(19)'));
                                break;
                                case 'Enter':
                                // prevent default action
                                e.preventDefault();
                                pressEqual();
                                break;
                                case 'Backspace':
                                pressClear();
                                break;
                                case 'Escape':
                                pressAllClear();
                                break;
                            }
                            });
                        </script>
                    


calculator - example 4

top
example: calculator

Don't divide by zero

0
code:
                    <div class="format">
                        <p class="warning">Don't divide by zero</p>
                        <div id="calculator4" class="calculator4">
                            <div id="viewer" class="viewer">0</div>
                            
                            <button class="btn4 num" data-num="7">7</button>
                            <button class="btn4 num" data-num="8">8</button>
                            <button class="btn4 num" data-num="9">9</button>
                            <button data-ops="plus" class="btn4 ops">+</button>
                                    
                            <button class="btn4 num" data-num="4">4</button>
                            <button class="btn4 num" data-num="5">5</button>
                            <button class="btn4 num" data-num="6">6</button>
                            <button data-ops="minus" class="btn4 ops">-</button>
                                    
                            <button class="btn4 num" data-num="1">1</button>
                            <button class="btn4 num" data-num="2">2</button>
                            <button class="btn4 num" data-num="3">3</button>
                            <button data-ops="divided by" class="btn4 ops">/</button>
            
                            <button data-ops="times" class="btn4 ops">*</button> 
                            <button class="btn4 num" data-num="0">0</button>
                            <button class="btn4 num" data-num=".">.</button>
                            
                            <button id="equals" class="btn4 equals" data-result="">=</button>
                        
                            <button id="clear4" class="btn4 clear4">C</button>
                        </div>
                        <button id="reset" class="btn4 reset">Reset Universe?</button>
                    </div>
                    <style>
                        .format{height: 80vh;}
                        /* Gradient text only on Webkit */
                        .warning {background: -webkit-linear-gradient(45deg, grey 10%, red 90%); background: linear-gradient(45deg, grey 10%, red 90%); 
                            -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; color: #8c5059; 
                            font-weight: 600; font-size: 1.25vw; margin: 0 auto 3vw; max-width: 15vw;}
                        /* Calculator after dividing by zero */
                        .broken {-webkit-animation: broken 2s; animation: broken 2s; transform: translate3d(0, -200vw, 0); opacity: 0;} 
                        /* viewer and keyboard */
                        #viewer {padding-left:1vw; color: blue; float: left; line-height: 3vw; text-align: left; text-overflow: ellipsis; border: 0.2vw solid green; 
                            overflow: hidden; width: 23vw; height: 3vw;}
                        .calculator4 {font-size: 1.25vw; margin: 0 auto; width: 25vw;}
                        .calculator4::before, .calculator4::after {content: " "; display: table;}
                        .calculator4::after {clear: both; }
                        #clear4{width: 23vw; height: 3vw; background: red;}
                        .btn4 {border: 0; background: rgba(42, 50, 113, 0.28); color: darkblue; cursor: pointer; float: left; font: inherit; margin: 0.25vw;  width: 5vw; 
                            height: 5vw; transition: all 0.5s;}
                        .btn4:hover {background: green;}
                        .btn4:focus {outline: 0; /* The value fade-ins that appear */}
                        .btn4:focus::after {-webkit-animation: zoom 1s; animation: zoom 1s;-webkit-animation-iteration-count: 1; animation-iteration-count: 1; 
                            -webkit-animation-fill-mode: both; animation-fill-mode: both; content: attr(data-num); cursor: default; font-size: 10vw; 
                            position: absolute;  top: 1.5vw; left: 50%; text-align: center; margin-left: -2.4vw;  opacity: 0;  width: 4.8vw; }
                        /* Same as above, modified for operators */
                        .ops:focus::after {content: attr(data-ops); margin-left: -21vw;  width: 42vw;}
                        /* Same as above, modified for result */
                        .equals:focus::after {content: attr(data-result); margin-left: -30vw; width: 60vw;} 
                        /* Reset button */
                        #reset { background: blue; color: orangered; font-weight: 400; padding: 0.5vw 1vw; position: relative; width: auto; height: auto; } 
                        #reset:hover {background: green; color: white;}
                        #reset.show {top: 499vw; -webkit-animation: fadein 4s; animation: fadein 4s;}
                        /* Animations */
                        /* Values that appear onclick */
                        @-webkit-keyframes zoom {
                            0% {transform: scale(0.2); opacity: 1; }
                            70% {transform: scale(1);}
                            100% {opacity: 0;}
                        }
                        @keyframes zoom {
                            0% {transform: scale(0.2); opacity: 1; }
                            70% {transform: scale(1);}
                            100% {opacity: 0;}
                        }
                        /* Division by zero animation */
                        @-webkit-keyframes broken {
                            0% {transform: translate3d(0, 0, 0); opacity: 1;}
                            5% {transform: rotate(5deg);}
                            15% {transform: rotate(-5deg);}
                            20% {transform: rotate(5deg);}
                            25% {transform: rotate(-5deg);}
                            50% {transform: rotate(45deg);}
                            70% {transform: translate3d(0, 2000px, 0); opacity: 1;}
                            75% {opacity: 0;}
                            100% {transform: translate3d(0, -2000px, 0);}
                        }
                        @keyframes broken {
                            0% {transform: translate3d(0, 0, 0); opacity: 1;}
                            5% {transform: rotate(5deg);}
                            15% {transform: rotate(-5deg);}
                            20% {transform: rotate(5deg);}
                            25% {transform: rotate(-5deg);}
                            50% {transform: rotate(45deg);}
                            70% {transform: translate3d(0, 2000px, 0); opacity: 1;}
                            75% {opacity: 0;}
                            100% {transform: translate3d(0, -2000px, 0);}
                        }
                        /* Reset button fadein */
                        @-webkit-keyframes fadein {
                            0% {top: 499vw; opacity: 0;}
                            50% {opacity: 0;}
                            100% {opacity: 1;}
                        }
                        @keyframes fadein {
                            0% {top: 499vw; opacity: 0;}
                            50% {opacity: 0;}
                            100% {opacity: 1;}
                        } 
                        @media (min-width: 420px) {
                            .calculator {width: 12vw;}
                            .viewer {width: 8.5vw;}
                        .btn4 {margin: 0.5vw;}
                        }
                    </style>
                    <script>
            
                        (function() {
                            "use strict";
                            // Shortcut to get elements
                            var el = function(element) {
                                if (element.charAt(0) === "#") { // If passed an ID...
                                    return document.querySelector(element); // ... returns single element
                                }
                                return document.querySelectorAll(element); // Otherwise, returns a nodelist
                            };
            
                            // Variables
                            var viewer = el("#viewer"), equals = el("#equals"), nums = el(".num"),  ops = el(".ops"), theNum = "",  oldNum = "", resultNum, operator; 
                            // When number is clicked, get the current number selected
                            var setNum = function() {
                                if (resultNum) { 
                                    theNum = this.getAttribute("data-num");
                                    resultNum = "";
                                } else {
                                    theNum += this.getAttribute("data-num");
                                }
                                viewer.innerHTML = theNum; 
                            };
                            // When an operator is clicked, pass number to oldNum and save operator
                            var moveNum = function() {
                                oldNum = theNum;
                                theNum = "";
                                operator = this.getAttribute("data-ops");
                                equals.setAttribute("data-result", ""); 
                            };
                            // When equals is clicked, calculate result
                            var displayNum = function() {
                                // Convert string input to numbers
                                oldNum = parseFloat(oldNum);
                                theNum = parseFloat(theNum);
                                // Perform operation
                                switch (operator) {
                                    case "plus":
                                        resultNum = oldNum + theNum;
                                        break;
                                    case "minus":
                                        resultNum = oldNum - theNum;
                                        break;
                                    case "times":
                                        resultNum = oldNum * theNum;
                                        break;
                                    case "divided by":
                                        resultNum = oldNum / theNum;
                                        break;
                                    // If equal is pressed without an operator, keep number and continue
                                    default:
                                        resultNum = theNum;
                                }
                                // If NaN or Infinity returned
                                if (!isFinite(resultNum)) {
                                    if (isNaN(resultNum)) { 
                                        resultNum = "You broke it!";
                                    } else { 
                                        resultNum = "Look at what you've done";
                                        el('#calculator4').classList.add("broken"); 
                                        el('#reset').classList.add("show");
                                                            
                                    }
                                }
                                // Display result, finally!
                                viewer.innerHTML = resultNum;
                                equals.setAttribute("data-result", resultNum);
                                // Now reset oldNum & keep result
                                oldNum = 0;
                                theNum = resultNum;
            
                            };
            
                        // When: Clear button is pressed. Clear everything
                        var clearAll = function() {
                            oldNum = "";
                            theNum = "";
                            viewer.innerHTML = "0";
                            equals.setAttribute("data-result", resultNum);
                        };
            
                        /* The click events */
                        // Add click event to numbers
                        for (var i = 0, l = nums.length; i < l; i++) {
                            nums[i].onclick = setNum;
                        }
            
                        // Add click event to operators
                        for (var i = 0, l = ops.length; i < l; i++) {
                            ops[i].onclick = moveNum;
                        }
                        // Add click event to equal sign
                        equals.onclick = displayNum;
            
                        // Add click event to clear button
                        el("#clear4").onclick = clearAll;
            
                        // Add click event to reset button
                        el("#reset").onclick = function() {
                            window.location = window.location;
                        };
            
                        }());
                    </script>