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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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.

Editor Settings

Code Indentation

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

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

HTML

            
              <div class="container">

  <div class="calculator">
    <div class="row">
      <div id="display">0</div>
    </div>
    <div class="row">
      <div class="btn ce">CE</div>
      <div class="btn clear">C</div>
      <div class="btn delete">←</div>
      <div class="btn operator" data-operator="/">÷</div>
    </div>
    <div class="row">
      <div class="btn num">7</div>
      <div class="btn num">8</div>
      <div class="btn num">9</div>
      <div class="btn operator" data-operator="*">×</div>
    </div>
    <div class="row">
      <div class="btn num">4</div>
      <div class="btn num">5</div>
      <div class="btn num">6</div>
      <div class="btn operator" data-operator="-">-</div>
    </div>
    <div class="row">
      <div class="btn num">1</div>
      <div class="btn num">2</div>
      <div class="btn num">3</div>
      <div class="btn operator" data-operator="+">+</div>
    </div>
    <div class="row">
      <div class="btn">±</div>
      <div class="btn num">0</div>
      <div class="btn" id="dot">.</div>
      <div class="btn" id="equal">=</div>
      
    </div>
  </div>
  <p class="note"><strong>Note</strong>: You can use your keyboard.</p>
</div>
            
          
!

CSS

            
              $primary-color: #009688;
$primary-text-color: #212121;
$dark-primary-color: #00796B;
$light-primary-color: #B2DFDB;
$text-icon-color: #FFFFFF;
$accent-color: #9E9E9E;
$key-width: 25%;

body {
  color: $text-icon-color;
  font-size: 22px;
  font-family: 'Montserrat', sans-serif;
  background-color: $light-primary-color;
  height: 100vh;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100%;
}

.calculator {
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
 background-color: $primary-text-color;
  height: 100%;
}

.note {
  text-align: center;
  font-size: .75em;
  color: $primary-text-color;
}

.row {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  & > * {
    width: $key-width;
  }
}

.btn {
  cursor: pointer;
  user-select: none;
  box-sizing: border-box;
  text-align: center;
  padding: 1em 0;
  transition: background-color .3s;
}

.btn:hover {
  background-color: $dark-primary-color;
}

.accent {
  background-color: $accent-color;
}

#display {
  box-shadow: 0 2px 5px rgba(0,0,0,0.26);
  z-index: 2;
  width: 100%;
  padding: 1em;
  text-align: right;
  background-color: white;
  color: $primary-text-color;
}

@media screen and (min-width: 460px) {
  .calculator {
    width: 460px;
    margin: 0 auto;
    height: auto;
  }
}
            
          
!

JS

            
              var helpers = {
  getLastItemInArray: function getLastItemInArray(arr) {
    return arr.length > 0 ? arr[arr.length - 1] : null;
  },

  hasChars: function hasChars(chars, str) {
    var chars = chars;
    return function(str) {
      if (typeof chars == "string" && chars.length === 1) {
        return str.indexOf(chars) !== -1;
      } else {
        for (var i = 0; i < chars.length; i++) {
          if (chars[i] === str) {
            return true;
          }
        }
        return false;
      }
    };
  },

  normalizeKey(e) {
    let key = e.key;
    let keyCode = e.keyCode;
    if (keyCode >= 96 && keyCode <= 105) {
      // Numpad keys
      keyCode -= 48;
      return String.fromCharCode(keyCode);
    }
    switch (key.toLowerCase()) {
      case "divide":
        return "/";
        break;
      case "add":
        return "+";
        break;
      case "subtract":
        return "-";
        break;
      case "multiply":
        return "*";
        break;
      case "decimal":
        return ".";
        break;
      default:
        return key;
    }
  }
};

function calculator() {
  var c = [],
    mathFunctions = {
      "+": function(a, b) {
        return (a + b).toString();
      },
      "-": function(a, b) {
        return (a - b).toString();
      },
      "*": function(a, b) {
        return (a * b).toString();
      },
      "/": function(a, b) {
        return (a / b).toString();
      }
    },
    validNumbers = "1234567890",
    validOperators = Object.keys(mathFunctions),
    containsDot = helpers.hasChars("."),
    containsNumber = helpers.hasChars(validNumbers),
    containsOperator = helpers.hasChars(validOperators);

  function calculate(arr) {
    var num1 = containsDot(arr[0]) ? parseFloat(arr[0]) : parseInt(arr[0]),
      operator = arr[1],
      num2 = containsDot(arr[2]) ? parseFloat(arr[2]) : parseInt(arr[2]);
    return mathFunctions[operator](num1, num2);
  }

  function addOperator(op) {
    var lastItem = helpers.getLastItemInArray(c);
    if (!lastItem) return;
    if (lastItem && containsOperator(lastItem)) {
      c.pop();
    }
    c.push(op);
    return c;
  }

  function computeTotal() {
    var len;
    if (containsOperator(helpers.getLastItemInArray(c))) {
      c.pop();
    }
    len = c.length;
    while (c.length > 1) {
      c = [calculate(c.slice(0, 3))].concat(c.slice(3, len));
    }
    return c[0];
  }

  function addDot() {
    var lastItem = helpers.getLastItemInArray(c);
    if (lastItem && containsDot(lastItem)) {
      return;
    }
    if (lastItem && !containsDot(lastItem) && !containsOperator(lastItem)) {
      c.pop();
      c.push(lastItem.concat("."));
    } else {
      c.push(".");
    }
  }

  function addNum(num) {
    var lastItem = helpers.getLastItemInArray(c);
    if (lastItem && !containsOperator(lastItem)) {
      c.pop();
      c.push(lastItem.concat(num));
    } else {
      c.push(num);
    }
    return c;
  }

  function clear() {
    c = [];
  }

  function deleteLastChar() {
    var lastItem = helpers.getLastItemInArray(c);
    if (lastItem) {
      c.pop();
      if (lastItem.length > 1) {
        c.push(lastItem.slice(0, lastItem.length - 1));
      }
    }
  }

  function clearLastEntry() {
    c.pop();
  }

  function display() {
    return c.length > 0 ? c.join(" ") : "0";
  }

  function isValidOperator(char) {
    return containsOperator(char);
  }

  function isValidNumber(char) {
    return containsNumber(char);
  }

  return {
    isValidOperator: isValidOperator,
    isValidNumber: isValidNumber,
    display: display,
    addOperator: addOperator,
    addDot: addDot,
    addNum: addNum,
    delete: deleteLastChar,
    computeTotal: computeTotal,
    clearLastEntry: clearLastEntry,
    clear: clear
  };
}

var octopus = {
  init: function octopusInit() {
    this.calc = calculator();
    view.init();
  },

  addNum: function octopusAddNum(e) {
    var num = typeof e === "string" ? e : this.innerHTML;
    octopus.calc.addNum(num);
    view.render();
  },

  addOperator: function octopusAddOperator(e) {
    const keyPressed = typeof e === "string";
    var operator = keyPressed ? e : e.target.dataset.operator;
    octopus.calc.addOperator(operator);
    view.render();
  },

  addDot: function octopusAddDot() {
    octopus.calc.addDot();
    view.render();
  },

  computeTotal: function octopusComputeTotal() {
    octopus.calc.computeTotal();
    view.render();
  },

  clear: function octopusClear() {
    octopus.calc.clear();
    view.render();
  },

  delete: function octopusDelete() {
    octopus.calc.delete();
    view.render();
  },

  clearLastEntry: function octopusClearLastEntry() {
    octopus.calc.clearLastEntry();
    view.render();
  },

  keyHandler: function keyHandler(e) {
    e.preventDefault();
    var keyPressed = helpers.normalizeKey(e),
      backspace = 8,
      enterKeyCode = 13,
      dotKeyCode = 46;
    if (octopus.calc.isValidNumber(keyPressed)) {
      octopus.addNum(keyPressed);
    } else if (octopus.calc.isValidOperator(keyPressed)) {
      octopus.addOperator(keyPressed);
    } else if (e.keyCode === enterKeyCode) {
      octopus.computeTotal();
    } else if (keyPressed === ".") {
      octopus.addDot();
    } else if (e.keyCode === backspace) {
      octopus.delete();
    }
  }
};

var view = {
  init: function viewInit() {
    var numberElements = document.getElementsByClassName("num");
    numberElements = [].slice.call(numberElements);
    numberElements.forEach(function addNumHandler(elem) {
      elem.addEventListener("click", octopus.addNum);
    });

    var operatorElements = [].slice.call(
      document.getElementsByClassName("operator")
    );
    operatorElements.forEach(function addOpHandler(elem) {
      elem.addEventListener("click", octopus.addOperator);
    });

    // TODO: Add event delegation

    document
      .getElementById("equal")
      .addEventListener("click", octopus.computeTotal);

    document.getElementById("dot").addEventListener("click", octopus.addDot);

    document.querySelector(".clear").addEventListener("click", octopus.clear);

    document.querySelector(".delete").addEventListener("click", octopus.delete);

    document
      .querySelector(".ce")
      .addEventListener("click", octopus.clearLastEntry);

    window.addEventListener("keydown", octopus.keyHandler);

    this.display = document.getElementById("display");
  },
  render: function viewRender() {
    this.display.innerHTML = octopus.calc.display();
  }
};

function ready(fn) {
  if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(octopus.init.bind(octopus));
            
          
!
999px

Console