Question

In: Computer Science

Calculator in JavaScript Project Standards: Students will use click events to capture user input. Students will...

Calculator in JavaScript

Project Standards:

  • Students will use click events to capture user input.
  • Students will use variables to store information needed by their application and keep track of their program’s state.
  • Students will use conditionals to control project flow.

Project Task

You will be building a simple calculator in the browser. It should be able to add, subtract, divide, and multiply. Your program should do the following:

  1. Display a standard calculator to the user (you have starter files to help you with this).
  2. You will need to make references to all the proper HTML elements you'll be using to display elements to the user.
  3. You should make variables to keep track of the 1st number, operator, 2nd number, and the result of the math.
  4. When a user clicks on a button it should work like a standard calculator.
    1. Every number they click should be captured and build the 1st number until they click an operator (Ex. If they click 1 and 8, your program should display 18 to them)
    2. Clicking an operator (+, -, x, =) should only work if they have clicked numbers first.
    3. A user can only fill out the 2nd number once they have filled out the 1st number and clicked an operator.
    4. The = key will only work if a user has clicked both a 1st number, an operator, and a 2nd number. When they have filled in all the necessary inputs, = will display the proper number to them (Ex. if they input 5, +, and 7, they should be displayed 12).
    5. The clear button will clear all prior input and allow the user to start over.
  5. Your JavaScript code will form the conditional logic to determine whether a clicked button should work or not.
  6. You should display the 1st number, the operator, the 2nd number, and the math output (sum, product, difference, quotient) to the user at the appropriate times.

STARTER HTML CODE

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Calculator Starter</title>

  <!-- Added a link to Bootstrap-->

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

</head>

<body>

  <div class="jumbotron">

    <h1 class="text-center">JavaScript Calculator</h1>

  </div>

  <div class="container">

    <div class="row">

      <!-- Calculator Card -->

      <div class="col-lg-4">

        <div class="card">

          <h3 class="card-header">Calculator</h3>

          <div class="card-body">

            <button id="button-1" class="btn btn-primary number" value="1">1</button>

            <button id="button-2" class="btn btn-primary number" value="2">2</button>

            <button id="button-3" class="btn btn-primary number" value="3">3</button>

            <button id="button-plus" class="btn btn-danger operator" value="plus">+</button>

            <br><br>

            <button id="button-4" class="btn btn-primary number" value="4">4</button>

            <button id="button-5" class="btn btn-primary number" value="5">5</button>

            <button id="button-6" class="btn btn-primary number" value="6">6</button>

            <button id="button-minus" class="btn btn-danger operator" value="minus">&minus;</button>

            <br><br>

            <button id="button-7" class="btn btn-primary number" value="7">7</button>

            <button id="button-8" class="btn btn-primary number" value="8">8</button>

            <button id="button-9" class="btn btn-primary number" value="9">9</button>

            <button id="button-multiply" class="btn btn-danger operator" value="times">&times;</button>

            <br><br>

            <button id="button-0" class="btn btn-primary number" value="0">0</button>

            <button id="button-divide" class="btn btn-danger operator" value="divide">&divide;</button>

            <button id="button-power" class="btn btn-danger operator" value="power">^</button>

            <button id="button-equal" class="btn btn-success equal" value="equals">=</button>

            <br><br>

            <button id="button-clear" class="btn btn-dark clear" value="clear">clear</button>

          </div>

        </div>

      </div>

      <!-- Result Card -->

      <div class="col-lg-6">

        <div class="card">

          <h3 class="card-header">Result</h3>

          <div class="card-body">

            <h1 id="first-number"></h1>

            <h1 id="operator"></h1>

            <h1 id="second-number"></h1>

            <hr>

            <h1 id="result"></h1>

          </div>

        </div>

      </div>

    </div>

  </div>

  <script src="main.js"></script>

</body>

</html>

STARTER JAVASCRIPT CODE

// BUTTONS ON THE PAGE

const numberButtons = document.querySelectorAll('.number');

const operatorButtons = document.querySelectorAll('.operator');

const equalButton = document.querySelector('.equal');

const clearButton = document.querySelector('.clear');

// TODO make references to all the proper HTML elements you'll be using to display elements to the user

// TODO make variables to keep track of the 1st number, operator, 2nd number, and the result of the math.

for(let i = 0; i < numberButtons.length; i++) {

  numberButtons[i].addEventListener('click', clickNumber);

}

for(let i = 0; i < operatorButtons.length; i++) {

  operatorButtons[i].addEventListener('click', clickOperator);

}

equalButton.addEventListener('click', clickEqualButton);

clearButton.addEventListener('click', clickClearButton);

function clickNumber(event) {

  console.log(event.target.value);

  // CODE GOES HERE

}

function clickOperator(event) {

  console.log(event.target.value);

  // CODE GOES HERE

}

function clickEqualButton() {

  // CODE GOES HERE

}

function clickClearButton() {

  // CODE GOES HERE

}

Solutions

Expert Solution

style.css // CSS File

body,
html {
    height: 100%;
    padding: 0;
    margin: 0;
}

body {
    background-color: #e8dcd0;
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-weight: 300;
    font-size: 16px;
}

a {
    outline: 0;
}

h1 {
    font-size: 9vh;
    color: #fff;
    margin: 0;
}



.container-fluid {
    padding: 0;
    height: 100%;
    position: relative;
}

#calculator {
    height: 100%;
    max-width: 100%;
    background-color: #99dccb;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background: -webkit-linear-gradient(#a9e8d8, #74beac); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(#a9e8d8, #74beac); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(#a9e8d8, #74beac); /* For Firefox 3.6 to 15 */
    background: linear-gradient(#99dccb, #61af9d); /* Standard syntax */
}
#header {
    padding: 0 10px;
    height: 11%;
}
#display,
#history {
    text-align: right;
    padding: 0 5%;
    overflow: hidden;
}

#display {
    width: 100%;
    background-color: #fff;
    opacity: .85;
    font-size: 13vh;
    height: 18%;
}

#history {
    width: 100%;
    border-top: 2px solid #99dccb;
    background-color: #fff;
    opacity: .85;
    font-size: 3.5vh;
    height: 5%;
}

#keypad {
    height: 61%;
}

.row {
    margin: 0;
    height: 20%;
}

.col-sm-3 {
    width: 23%;
    margin: 2px;
}

.key {
    color: #fff;
    height: 20%;
}

.btn {
    font-size: 7vh;
}
#delete {
    font-variant: small-caps;
    font-size: 6vh;
}
#decimal {
    font-size: 6rem;
    line-height: 0;
}
footer {
    font-size: 3vh;
    height: 5%;
    color: #fff;
}
footer a, footer a:active, footer a:hover {
    color: #fff;
    text-decoration: underline;
}

@media (min-width: 769px) {
    #calculator {
        width: 400px;
        height: 720px;
        margin-top: 75px;
        border-radius: 10px;
    }
    h1 {
        font-size: 3.5em;
        padding-top: 6px;
    }
    #header {
        border-radius: 10px;
    }
    #display {
        font-size: 5em;
    }
    #history {
        font-size: 1.3em;
    }
    .btn {
        font-size: 2.2em;
    }
    #delete {
    font-size: 2.4em;
}
    footer {
        font-size: 1.1em;
    }
}

script.js //JavaScript File

$(document).ready(function () {

    var calcStr = ""; // main display
    var histStr = ""; // history display
    var total = ""; // running total
    var visible = false; //main display
    var dpoint_active = true; // able to create decimal
    var oper_active = true; // able to use operator

    //get data when calculator key is clicked
    document.getElementById('keypad').addEventListener('click', getKey);

    function getKey(k) {
        var key = k.target.id;
        switch (key) {
            case 'zero': key = 0;
                break;
            case 'one': key = 1;
                break;
            case 'two': key = 2;
                break;
            case 'three': key = 3;
                break;
            case 'four': key = 4;
                break;
            case 'five': key = 5;
                break;
            case 'six': key = 6;
                break;
            case 'seven': key = 7;
                break;
            case 'eight': key = 8;
                break;
            case 'nine': key = 9;
                break;
        }
        compute(key);
    }

    //display and calulate
    function displayIt(display, history) {
        document.getElementById("display").innerHTML = display;
        document.getElementById("history").innerHTML = history;
    }

    function calcIt(show, func) {
        calcStr += show;
        histStr += show;
        total += func;
        displayIt(calcStr, histStr);
    }

    function deleteOne() {
        calcStr = calcStr.slice(0, -1);
        histStr = histStr.slice(0, -1);
        total = total.slice(0, -1);
        displayIt(calcStr, histStr);
    }

    function compute(data) {
        //NUMBERS
        if (calcStr === "" && data === 0) {
            return 0;
        }

        if (data >= 0 && data <= 9) {
            if (visible) {
                calcStr = "";
                histStr = ""
                total = "";
                visible = false;
            }

            oper_active = true;
            calcIt(data, data);
        }

        //DECIMAL
        if (data == "decimal") {
            if (dpoint_active === false) {
                return 0;
            }
            if (visible || calcStr == 0 || histStr == 0) {
                calcStr = "0.";
                histStr = "0.";
                total = "0.";
                visible = false;
                displayIt(calcStr, histStr);
                dpoint_active = false;
            } else {
                calcIt(".", ".");
                dpoint_active = false;
            }
        }

        //OPERATORS
        if (data == "add") {
            if (total == "") {
                return 0;
            }
            if (oper_active == false) {
                deleteOne();
            }
            visible = false;
            dpoint_active = true;
            calcIt("+", "+");
            oper_active = false;
        }
        if (data == "subtract") {
            if (total == "") {
                return 0;
            }
            if (oper_active == false) {
                deleteOne();
            }
            visible = false;
            dpoint_active = true;
            calcIt("-", "-");
            oper_active = false;
        }
        if (data == "multiply") {
            if (total == "") {
                return 0;
            }
            if (oper_active == false) {
                deleteOne();
            }
            visible = false;
            dpoint_active = true;
            oper_active = false;
            calcIt("x", "*");
        }
        if (data == "divide") {
            if (total == "") {
                return 0;
            }
            if (oper_active == false) {
                deleteOne();
            }
            visible = false;
            dpoint_active = true;
            oper_active = false;
            calcIt("/", "/");
        }

        //EQUALS
        if (data == "equals") {
            if (total == "" || visible) {
                return 0;
            }
            visible = true;
            dpoint_active = true;
            histStr += " = \xa0" + eval(total);
            displayIt(eval(total), histStr);
            total = document.getElementById("display").innerHTML;
            calcStr = total;
        }

        //CLEAR
        if (data == "clear") {
            calcStr = "";
            histStr = "";
            total = "";
            visible = false;
            dpoint_active = true;
            displayIt("0", "0");
        }

        //DELETE
        if (data == "delete") {
            if (visible == true || calcStr == "" || calcStr.length == 1) {
                calcStr = "0";
                histStr = "0";
                displayIt(calcStr, histStr);
                return 0;
            }

            deleteOne();

        }
        //ERRORS

        if (calcStr.length > 25 || total == "NaN") {
            displayIt("Error","0");
            return 0;
        }
        console.log("***")
        console.log(`Display ${calcStr}`);
        console.log(`History ${histStr}`);
        console.log(`Total ${total}`);
        console.log("---");

    }
});

index.html // Calculator

<!DOCTYPE html>
<html>

<head>
    <title>Javascript Calculator</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
 
    <div class="container-fluid">
        <div id="calculator">
            <div id="header">
                <h1 class="text-center">JS Calculator</h1>
            </div>
            <div id="display">
                0
            </div>
            <div id="history">
                0
            </div>
            <div id="keypad">
                <div class="row text-center">
                    <div type="button" id="clear" class="btn key col-sm-3">C</div>
                    <div type="button" id="inv" class="btn key col-sm-3"></div>
                    <div type="button" id="percent" class="btn key col-sm-3"></div>
                    <div type="button" id="divide" class="btn key col-sm-3">&divide;</div>
                </div>
                <div class="row text-center">
                    <div type="button" id="seven" class="btn key col-sm-3">7</div>
                    <div type="button" id="eight" class="btn key col-sm-3">8</div>
                    <div type="button" id="nine" class="btn key col-sm-3">9</div>
                    <div type="button" id="multiply" class="btn key col-sm-3">&times;</div>
                </div>
                <div class="row text-center">
                    <div type="button" id="four" class="btn key col-sm-3">4</div>
                    <div type = "button" id="five" class="btn key col-sm-3">5</div>
                    <div type="button" id="six" class="btn key col-sm-3">6</div>
                    <div type="button" id="subtract" class="btn key col-sm-3">&minus;</div>
                </div>
                <div class="row text-center">
                    <div type="button" id="one" class="btn key col-sm-3">1</div>
                    <div type="button" id="two" class="btn key col-sm-3">2</div>
                    <div type="button" id="three" class="btn key col-sm-3">3</div>
                    <div type="button" id="add" class="btn key col-sm-3">+</div>
                </div>
                <div class="row text-center">
                    <div type="button" id="decimal" class="btn key col-sm-3">.</div>
                    <div type="button" id="zero" class="btn key col-sm-3">0</div>
                    <div type="button" id="delete" class="btn key col-sm-3">del</div>
                    <div type="button" id="equals" class="btn key col-sm-3">=</div>
                </div>
            </div>
            <footer class="text-center">
  
            </footer>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="script.js"></script>
</body>

</html>

Related Solutions

Calculator in JavaScript. No use of switch statements or CSS. Project Standards: Students will use click...
Calculator in JavaScript. No use of switch statements or CSS. Project Standards: Students will use click events to capture user input. Students will use variables to store information needed by their application and keep track of their program’s state. Students will use conditionals to control project flow. Project Task You will be building a simple calculator in the browser. It should be able to add, subtract, divide, and multiply. Your program should do the following: Display a standard calculator to...
Write in javaScript: User input 5 words in one input, and print out the longest word.
Write in javaScript: User input 5 words in one input, and print out the longest word.
using C language Create a bitwise calculator that ask user for input two input, first int,...
using C language Create a bitwise calculator that ask user for input two input, first int, bitwise operation, second int (i.e 5 & 9) only those bitwise operation are allowed: & ~ ^ | << >>. If user uses wrong operators stop program and ask again. Convert the first int and second int into 8 BITS binary (00000000) and use bitwise operator given by user to either AND, OR, XOR, etc (ie 1001 & 1111)
USE CALCULATOR AND SHOW EVERYSTEP USING CALCULATOR INCLUDING THE NUMBERS USE INPUT IN THE TEST. New...
USE CALCULATOR AND SHOW EVERYSTEP USING CALCULATOR INCLUDING THE NUMBERS USE INPUT IN THE TEST. New road signs are made with the intention of improving visibility for drivers. Highway safety engineers setup a test course that included both the old and new signs. Volunteers drove the course and rated the old and new signs in terms of visibility? (2 points each) a) Write the null and alternative hypotheses in words using “improved visibility” and “not improved visibility”. b) Describe a...
Using forms in Access lets you customize how you want to capture input from the user...
Using forms in Access lets you customize how you want to capture input from the user and screen the data if needed. If you were user entering data for a report, what are some of the things that make it easy for you to complete your task?
Create a project that gets input from the user. ( Name the project main.cpp) Ask the...
Create a project that gets input from the user. ( Name the project main.cpp) Ask the user for a value for each side of the triangle. Comment your code throughout. Include your name in the comments. Submit the plan-Psuedo code (include Flowchart, IPO Chart) and the desk check with each submission of your code. Submit the plan as a pdf. Snips of your output is not a plan. Save the plan and desk check as a pdf Name the code...
Write application in C# that enables a user to: Use Methods for user input and calculations...
Write application in C# that enables a user to: Use Methods for user input and calculations input the grade and number of credit hours for any number of courses. Calculate the GPA on a 4.0 scale using those values. Grade point average (GPA) is calculated by dividing the total amount of grade points earned, sometimes referred to as quality points, by the total number of credit hours attempted. For each hour, an A receives 4 grade or quality points, a...
Please Use JavaScript and P5 1) Greeter Create an page with an input, and a button....
Please Use JavaScript and P5 1) Greeter Create an page with an input, and a button. When the button is clicked, output the phrase "Hello {Name}" to the developer console, with {Name} being the value the user put into the input field. Use a function that takes the name as an argument, and returns the full phrase as its output.
Create a web calculator with JavaScript. Only four operations (Add, Sub, Multiplication, and Division) Use a...
Create a web calculator with JavaScript. Only four operations (Add, Sub, Multiplication, and Division) Use a CE button to cancel the operation.    Use the following website or any online resource as a reference. Don’t use their CSS or any other code.                 https://freshman.tech/calculator/ I am trying to learn please make comments then I will understand better.
Must use prompts to get input from user and alerts for output. Do not use jQuery...
Must use prompts to get input from user and alerts for output. Do not use jQuery or document.getElementById to solve these problems. User input validation is not required. Assume the user will enter correct values and write your program. Program should run once and exit. 1. Filenames: tip.html & tip.js Write a Tip program where the user enters a restaurant bill total. The program should then display two amounts: a 15 percent tip and a 20 percent tip. The output...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT