Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/react@16.0.0-rc.3/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16.0.0-rc.3/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/prop-types@15.6.0/prop-types.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="./style.css" />
    <link
      href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap&subset=latin-ext"
      rel="stylesheet"
    />
    <script
      src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
      integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
      integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
      crossorigin="anonymous"
    ></script>

    <title>Calculator</title>
  </head>
  <body>
    <div id="root"></div>


  </body>
</html>

              
            
!

CSS

              
                body {
  margin: 0;
  padding: 0;
}
#root {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

#main-container {
  width: 40vh;
  height: 65vh;
  display: grid;
  grid-template-areas:
    "operations-display operations-display operations-display operations-display"
    "display display display display"
    "line line line line"
    "add subtract multiply divide"
    "seven eight nine clear"
    "four five six clear"
    "one two three ."
    "zero zero decimal equals";
  background: linear-gradient(90deg, rgb(254, 234, 204), rgb(225, 234, 249));
  border-radius: 25px;
  padding-bottom: 10px;
  box-shadow: 5px 3px 9px 0px rgba(0, 0, 0, 0.1);
}

button {
  border: none;
  background-color: rgb(255, 255, 255, 0.01);
  font-size: 1.2em;
  width: 10vh;
}
#display {
  grid-area: display;
  font-size: 3em;
  font-weight: 300;
  text-align: end;
  padding-right: 15px;
  padding-bottom: 15px;
}

#operations-display {
  grid-area: operations-display;
  font-size: 18px;
  height: 18vh;
  font-size: 1em;
  font-weight: 300;
  text-align: end;
  padding-top: 15vh;
  padding-right: 15px;
  margin: 0 0 0 0;
}

#line {
  grid-area: line;
  border-top: 1px solid #2125297e;
  margin-right: 15px;
  margin-left: 15px;
  padding-bottom: 20px;
}

.operationsButton {
  color: rgb(223, 28, 106);
  height: 5vh;
  width: 5vh;
  font-weight: 600;
  justify-self: center;
}

#add {
  grid-area: add;
}
#subtract {
  grid-area: subtract;
}
#multiply {
  grid-area: multiply;
}
#divide {
  grid-area: divide;
}
#seven {
  grid-area: seven;
}

#eight {
  grid-area: eight;
}
#nine {
  grid-area: nine;
}
#clear {
  grid-area: clear;
}
#four {
  grid-area: four;
}
#five {
  grid-area: five;
}
#six {
  grid-area: six;
}

#one {
  grid-area: one;
}
#two {
  grid-area: two;
}
#three {
  grid-area: three;
}
#equals {
  grid-area: equals;
  border-radius: 50%;
  background-color: rgb(223, 28, 106);
  color: white;
  width: 6vh;
  height: 6vh;
  display: block;
  margin: auto;
  box-shadow: 3px 2px 10px 0px rgba(0, 0, 0, 0.2);
  text-align: center;
  font-size: 1.5em;
}
#equals span {
  line-height: 1.5em;
  /* padding-top: 2.5vh; */
}

#zero {
  grid-area: zero;
}
#decimal {
  grid-area: decimal;
}

              
            
!

JS

              
                function App() {
  return <Calculator />;
}

const numbers = {
  zero: 0,
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  decimal: "."
};

const mathOperations = /[+/*]/;

const findLastNumbers = arr => {
  let newArr = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    if (/[-+/*]/.test(arr[i])) {
      break;
    }
    newArr.push(arr[i]);
  }
  return newArr.reverse();
};

const deleteLastSigns = arr => {
  let newArr = [...arr];
  newArr.pop();
  for (let i = arr.length - 1; i >= 0; i--) {
    if (mathOperations.test(arr[i])) {
      newArr.pop();
    }
  }
  return newArr;
};

const countDecimals = value => {
  if (Math.floor(value) === value) {
    return 0;
  }
  return value.toString().split(".")[1].length || 0;
};

class Calculator extends React.Component {
  constructor() {
    super();
    this.state = {
      display: "0",
      operationsDisplay: []
    };

    this.handleClickNumber = this.handleClickNumber.bind(this);
    this.handleClickMath = this.handleClickMath.bind(this);
    this.handleClickEquals = this.handleClickEquals.bind(this);
    this.handleClickClear = this.handleClickClear.bind(this);
    this.handleClickMinus = this.handleClickMinus.bind(this);
  }

  handleClickNumber(event) {
    if (event.target.id === "zero" && this.state.display === "0") {
      return null;
    }
    let lastSign = this.state.operationsDisplay[
      this.state.operationsDisplay.length - 1
    ];
    if (
      event.target.id === "decimal" &&
      this.state.display.includes(".")
    ) {
      return null;
    }

    if (
      event.target.id === "decimal" &&
      this.state.display === "0" &&
      this.state.operationsDisplay[0] === undefined
    ) {
      this.setState({ display: "0", operationsDisplay: ["0"] });
    }

    let newNum = numbers[event.target.id];
    this.setState(prevState => {
      let newArr = findLastNumbers(prevState.operationsDisplay);
      return {
        operationsDisplay: [...prevState.operationsDisplay, newNum],
        display: [...newArr, newNum].join("")
      };
    });
  }

  handleClickMath(event) {
    let { name } = event.target;

    let lastSign = this.state.operationsDisplay[
      this.state.operationsDisplay.length - 1
    ];

    // const mathOp = /[+-/*]/;

    if (/\d/.test(lastSign)) {
      this.setState(prevState => {
        return {
          operationsDisplay: [...prevState.operationsDisplay, name],
          display: name
        };
      });
    } else {
      if (lastSign === "-") {
        this.setState(prevState => {
          let newArr = deleteLastSigns(prevState.operationsDisplay);
          return {
            operationsDisplay: [...newArr, name],
            display: name
          };
        });
      } else if (
        lastSign === "+" ||
        lastSign === "*" ||
        lastSign === "/"
      ) {
        this.setState(prevState => {
          let newArr = [...prevState.operationsDisplay];
          newArr.pop();
          return {
            operationsDisplay: [...newArr, name],
            display: name
          };
        });
      } else if (lastSign === undefined) {
        this.setState(prevState => {
          let newArr = [];
          return {
            operationsDisplay: [...newArr, prevState.display, name],
            display: name
          };
        });
      }
    }
  }

  handleClickMinus(event) {
    let { name } = event.target;

    let lastSign = this.state.operationsDisplay[
      this.state.operationsDisplay.length - 1
    ];

    if (/[\d]/.test(lastSign)) {
      this.handleClickMath(event);
    } else {
      if (lastSign === "+" || lastSign === "*" || lastSign === "/") {
        this.setState(prevState => {
          return {
            operationsDisplay: [...prevState.operationsDisplay, "-"],
            display: "-"
          };
        });
      } else if (lastSign === undefined) {
        this.setState(prevState => {
          let newArr = [];
          return {
            operationsDisplay: [...newArr, prevState.display, name],
            display: name
          };
        });
      }
    }
  }

  handleClickEquals() {
    let lastSign = this.state.operationsDisplay[
      this.state.operationsDisplay.length - 1
    ];

    if (!/\d/.test(lastSign)) {
      return null;
    }

    let result = eval(this.state.operationsDisplay.join(""));

    if (countDecimals(result) > 4) {
      result = result.toFixed(5);
    }

    this.setState(prevState => {
      return {
        operationsDisplay: [],
        display: result
      };
    });
  }

  handleClickClear() {
    this.setState({ display: "0", operationsDisplay: [] });
  }

  render() {
    return (
      <div id="main-container">
        <p id="operations-display">{this.state.operationsDisplay}</p>
        <div id="display">{this.state.display}</div>
        <div id="line"></div>

        <button onClick={this.handleClickNumber} id="seven">
          7
        </button>
        <button onClick={this.handleClickNumber} id="eight">
          8
        </button>
        <button onClick={this.handleClickNumber} id="nine">
          9
        </button>
        <button onClick={this.handleClickNumber} id="four">
          4
        </button>
        <button onClick={this.handleClickNumber} id="five">
          5
        </button>
        <button onClick={this.handleClickNumber} id="six">
          6
        </button>
        <button onClick={this.handleClickNumber} id="one">
          1
        </button>
        <button onClick={this.handleClickNumber} id="two">
          2
        </button>
        <button onClick={this.handleClickNumber} id="three">
          3
        </button>
        <button onClick={this.handleClickNumber} id="zero">
          0
        </button>

        <button
          onClick={this.handleClickMath}
          className="operationsButton"
          id="add"
          name="+"
        >
          +
        </button>
        <button
          onClick={this.handleClickMinus}
          className="operationsButton"
          id="subtract"
          name="-"
        >
          -
        </button>
        <button
          onClick={this.handleClickMath}
          className="operationsButton"
          id="multiply"
          name="*"
        >
          *
        </button>
        <button
          onClick={this.handleClickMath}
          className="operationsButton"
          id="divide"
          name="/"
        >
          /
        </button>

        <button id="decimal" onClick={this.handleClickNumber}>
          .
        </button>

        <button onClick={this.handleClickClear} id="clear">
          c
        </button>

        <button onClick={this.handleClickEquals} id="equals">
          <span>=</span>
        </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

              
            
!
999px

Console