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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <div class="mainbox container">
  <div id="title">
    <h1>Pocket Calculator</h1>
  </div>
  <div id="output">   
    <div>
      <span id="outputRes">0</span><br/>
      <span id="outputFormula"></span>     
    </div>
  </div>
  <!-- rows of buttons -->

    <div class="row row-centered">
      <div class="col-xs-1 col-centered  greykey">
        <div id="allClear" class="keytext red">AC</div>
      </div>
        <div class="col-xs-1 col-centered greykey">
          <div id="clearEntry" class="keytext red">CE</div>
        </div>
        <div class="col-xs-1 col-centered" style="width: 62px"></div>
        <div class="col-xs-1 col-centered key">
          <div  id="kdiv" class="keytext">÷</div>
        </div>
    </div>
  
    <div class="row row-centered">
      <div class="col-xs-1 col-centered key">
        <div id="k7" class="keytext">7</div>
      </div>
      <div class="col-xs-1 col-centered key">
          <div id="k8" class="keytext">8</div>
      </div>
      <div class="col-xs-1 col-centered key">
          <div id="k9" class="keytext">9</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="kx" class="keytext">x</div>
      </div>
    </div>
    <div class="row row-centered">
      <div class="col-xs-1 col-centered key">
        <div id="k4" class="keytext">4</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="k5" class="keytext">5</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="k6" class="keytext">6</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="kmin" class="keytext">-</div>
      </div>
    </div>
    <div class="row row-centered">
      <div class="col-xs-1 col-centered key">
        <div id="k1" class="keytext">1</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="k2" class="keytext">2</div>
      </div>
        <div class="col-xs-1 col-centered key">
          <div id="k3" class="keytext">3</div>
      </div>
        <div class="col-xs-1 col-centered key">
          <div id="kpl" class="keytext">+</div>
      </div>
       
    </div>
    <div class="row row-centered">
      <div class="col-xs-1 col-centered key">
        <div id="k0" class="keytext">0</div>
      </div>
      <div class="col-xs-1 col-centered key">
        <div id="kpt" class="keytext">.</div>
      </div>
      <div class="col-xs-2 col-centered key fatkey">
        <div id="keq" class="keytext">=</div>
      </div>      
    </div>

</div>
              
            
!

CSS

              
                @font-face {
  font-family: 'Digital-7';
  src: url('https://dl.dropboxusercontent.com/s/smdvthcbpy5p6oq/digital-7.ttf');
/*   src: url('https://cors-anywhere.herokuapp.com/http://coding.citytravelling.me.uk/assets/digital-7.ttf'); */
}
/* Font by Style7
  http://www.styleseven.com/ 
  Found downloaded from:
  http://www.fontspace.com/profile/style-7
*/

body {
  background-image: 
    linear-gradient(#646, #181526);
  background-size: cover;
  background-repeat: no-repeat;
  height: 100vh;  
}


#output {
  width: 96%;
  height: 6em;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 25px;
  border: 2px solid rgba(90,109,140,0.4);
  border-radius: 6px;
  background-color: #7E8C74;
  font-family: 'Digital-7', 'monospace';
}
#output div {
  text-align: right;
  padding-right: 10px;
}
#outputRes { 
  font-size: 2.2em;
}
#outputFormula {
  font-size: 1.4em;
}

.mainbox {
  margin-left: auto;
  margin-right: auto;
  width: 350px;
  padding: 10px 20px 20px 20px;
  background: #AFAFAF;
  margin-top: 40px;
  text-align: center;
      border-radius: 10px;
}
.container {
      display: -webkit-block;
    display: block;
  justify-content: space-between;
}
.title {
    width: 700px;
    height: 550px;
}


.row {
  padding: 5px 5px 5px 5px;
  height:
}
/* centered columns styles */
.row-centered {
    text-align:center;
   background-color: #E1E1E1;
}
.col-centered {
    display:inline-block;
    float:none;
    /* reset the text-align */
    text-align:center;
    /* inline-block space fix */
    margin-right:-4px;
}

/**
 * KEYS.css
 *
 * A simple stylesheet for rendering beautiful keyboard-style elements.
 *
 * Author:  Michael Hüneburg
 * Website: http://michaelhue.com/keyscss
 * License: MIT License (see LICENSE.txt)
 */

/* Base style, essential for every key. */
kbd, .key {
	display: inline-block;
	min-width: 1em;
  width: 55px;
	padding: 2px 3px;
  height: 2.5em;
  font: bold .85em/1 "Lucida Grande", Lucida, Arial, sans-serif;

	text-decoration: none;
	-moz-border-radius: .3em;
	-webkit-border-radius: .3em;
	border-radius: .3em;
	border: none;
	cursor: pointer;
	-moz-user-select: none;
	-webkit-user-select: none;
	user-select: none;
    margin: 0 2px 0 2px;
}
kbd[title], .key[title] {
	cursor: help;
}

.key .keytext, .greykey .keytext {
    font-size: 2em;
    vertical-align: middle;
}
.greykey {
  background: rgb(190, 190, 190);
	display: inline-block;
	min-width: 1em;
  width: 55px;
	padding: 2px 3px;
  height: 2.5em;
  font: bold .85em/1 "Lucida Grande", Lucida, Arial, sans-serif;
	text-align: center;
	text-decoration: none;
	-moz-border-radius: .3em;
	-webkit-border-radius: .3em;
	border-radius: .3em;
	border: none;
	cursor: pointer;
	-moz-user-select: none;
	-webkit-user-select: none;
	user-select: none;
    margin: 0 2px 0 2px;
  /* box shadow */
  -moz-box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
	-webkit-box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
	box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
}
.greykey:hover {
  background: rgb(140, 140, 140);
}

.fatkey {
    width: 118px;   
}

.key:hover , .keytext:hover {
  background: rgb(55, 55, 55); 
  color: rgb(230,230,230);
}

/* Dark style for display on light background. This is the default style. */
kbd, kbd.dark, .dark-keys kbd, .key, .key.dark, .dark-keys .key {
	background: rgb(80, 80, 80);
	background: -moz-linear-gradient(top, rgb(60, 60, 60), rgb(80, 80, 80));
	background: -webkit-gradient(linear, left top, left bottom, from(rgb(60, 60, 60)), to(rgb(80, 80, 80)));
	color: rgb(250, 250, 250);
	text-shadow: -1px -1px 0 rgb(70, 70, 70);
	-moz-box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
	-webkit-box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
	box-shadow: inset 0 0 1px rgb(150, 150, 150), inset 0 -.05em .4em rgb(80, 80, 80), 0 .1em 0 rgb(30, 30, 30), 0 .1em .1em rgba(0, 0, 0, .3);
}

.keytext.red {
    color: rgb(220, 0, 0);
 	background: rgb(200, 200, 200);
	background: -moz-linear-gradient(top, rgb(210, 210, 210), rgb(222, 222, 210));
}
.keytext.red:hover {
  background: none;
  color: rgb(180,0,0);
}
/* Light style for display on dark background. */
/*kbd.light, .light-keys kbd, .key.light, .light-keys .key {
	background: rgb(250, 250, 250);
	background: -moz-linear-gradient(top, rgb(210, 210, 210), rgb(255, 255, 255));
	background: -webkit-gradient(linear, left top, left bottom, from(rgb(210, 210, 210)), to(rgb(255, 255, 255)));
	color:  rgb(50, 50, 50);
	text-shadow: 0 0 2px rgb(255, 255, 255);
	-moz-box-shadow: inset 0 0 1px rgb(255, 255, 255), inset 0 0 .4em rgb(200, 200, 200), 0 .1em 0 rgb(130, 130, 130), 0 .11em 0 rgba(0, 0, 0, .4), 0 .1em .11em rgba(0, 0, 0, .9);
	-webkit-box-shadow: inset 0 0 1px rgb(255, 255, 255), inset 0 0 .4em rgb(200, 200, 200), 0 .1em 0 rgb(130, 130, 130), 0 .11em 0 rgba(0, 0, 0, .4), 0 .1em .11em rgba(0, 0, 0, .9);
	box-shadow: inset 0 0 1px rgb(255, 255, 255), inset 0 0 .4em rgb(200, 200, 200), 0 .1em 0 rgb(130, 130, 130), 0 .11em 0 rgba(0, 0, 0, .4), 0 .1em .11em rgba(0, 0, 0, .9);
}
*/
              
            
!

JS

              
                $(function() {

 
  // Handle AC and CE keys
  $(".greykey").on("click", function(e) {
	  	var valEntered = e.currentTarget.innerText;
      var valCur =$("#outputFormula").text();

	// get rid of any extra characters by only passing the 1st one. 
       valEntered = valEntered.charAt(0);
            
      switch (valEntered) {
          case "C": // Clear entry
          	// get last number entered
        		if (valCur.length > 0 &&         				
        				!valCur.includes("+") &&
        				!valCur.includes("-") &&
        				!valCur.includes("*") &&
						!valCur.includes("/")) {
	            $("#outputFormula").html("");
	          } else {
	          	
	          	var pos = valCur.length;

	          	while(pos > 0) {
	          		var chTest = valCur[valCur.length-1];
                if (testNum(chTest) || chTest == '.' || chTest == '=') {
                  valCur = valCur.substr(0,valCur.length-1);
                  pos --;							
                } else if (testMathFunc(chTest)) {
                  pos = 0;
                } else {											
                  pos --;
                }			          	
	          	}
	          	$("#outputFormula").html(valCur);
	          }    		      	

          break;
          default: // AC (all clear) clicked
          	$("#outputRes").html("0");
          	$("#outputFormula").html("");
          break;
      }
	});
  
  
  $(".key").on("click", process);
  $(document).on('keyup', process);
  
  function process(e) {
    // TODO: add +/- key ...so you can do eg. 5/-5
    // check if a key was pressed:
    var btnPushed;
    if (!e.currentTarget.innerText && e.key) {
      // key press
      btnPushed = e.key;
    } else {
      // mouse click
      btnPushed = e.currentTarget.innerText;
    }
    
    // check for resolved previous formula so we can start again
    var formula = $("#outputFormula").text();
    if (formula.substr(formula.length - 1) === "=") {
      $("#outputFormula").text("");
    }
    var valEntered = btnPushed;
    var valCur = $("#outputFormula").text();

    // get rid of any extra characters by only passing the 1st one. 
    valEntered = valEntered.charAt(0);

    switch (valEntered) {
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
	      	if (valCur.length === 0) {
	            $("#outputFormula").html(valEntered); 
	          } else if (valCur.length === 1 && valCur.charAt(0) == '0') {
	          	// if there is only 1 zero, overwrite it.
	          	$("#outputFormula").html(valEntered);
	         }	else if (valCur.charAt(valCur.length -1) == '0') {
	            // test if we have an operator...
	         	var lastNumIdx = testIfHaveOperator(valCur);
	         	var latestNumber = (lastNumIdx > -1) ? 
	         											valCur.substr(lastNumIdx, valCur.length - 1) : 
	         											valCur.substr(0, valCur.length);
	         	if (latestNumber.indexOf('.') === -1) {
	         	// wipe out the last digit as it's a zero if no decimal points
	            	valCur = valCur.substring(0, valCur.length - 1);
	         	}
	          	$("#outputFormula").html(valCur + valEntered);
	          } else {
	          	$("#outputFormula").html(valCur + valEntered);	            
	          }

      break;
      case "0":
        // testing start of string

        		var testZero = new RegExp('0*.?0+');
            //  surpress leading zeros and allow 11100110101 type
	        	if (valCur == "0") {
	        		$("#outputFormula").html("0");
		        	break;
	   		    }     	
        
       		if (valCur.length === 0) {
	            $("#outputFormula").html( valEntered); 
	          } else if (valCur == 0 && valCur.charAt(valCur.length -1) != '.') {
	          		if (parseFloat(valCur) || testZero.test(valCur) ) {
	          	 		$("#outputFormula").html(valCur + valEntered);
	          	 	} else {
	          	 		$("#outputFormula").html("0" );
	          	 	}
	          	
	          }  else if (valCur.charAt(valCur.length -1) != '0') {
	           // stop last number entered having leading zeros
	           // TODO: check if ZERO!!!
	           	$("#outputFormula").html(valCur + valEntered);	            
	          } else {
	          	var testLastNum = '';
					
					// got operators, is it not the 1st number?
					var opIndex = testIfHaveOperator (valCur);
	          	if (opIndex > -1) {
	          		var idx = valCur.length -1;
	          		while (valCur[idx] != '+' &&
		          			valCur[idx] != '-' &&
		          			valCur[idx] != '*' &&
		          			valCur[idx] != '/') {
	          	 		testLastNum += valCur[idx];	   
	          	 		idx--;       	 	
	          		}
	          		if (testLastNum === valEntered) return; // both Zero
	          		if (parseFloat(testLastNum) || testZero.test(testLastNum) ) {
	          	 		$("#outputFormula").html(valCur + valEntered);
	          	 	}
	          	} else {
	          		testLastNum = valCur;
	          		
	          		if (parseFloat(testLastNum) || testZero.test(testLastNum) ) {
	          	 		$("#outputFormula").html(valCur + valEntered);
	          	 	}
	          	}
	          	 
	          	 
	          }
			break;           
      case ".":
        if (valCur.length == 0) {
          $("#outputFormula").html("0" + valEntered);
        } else if (testMathFunc(valCur[0]) && valCur.length == 1) {
          $("#outputFormula").html(valCur + "0" + valEntered);
        } else if (checkExpression(valCur)) { // test for valid numbers
          // test last number entered if it is a decimal (has a dot)
          if (valCur.charAt(valCur.length - 1) !== ".") {
            $("#outputFormula").html(valCur + ".");
          }

        } else {
          var lastEntered = valCur.split('')[valCur.length-1].match(/[\-|\+|\*|\/]/)
          if (lastEntered) {
            $("#outputFormula").html(valCur + "0" + valEntered);
          } else {
            $("#outputFormula").html(valCur);
          }
        }

        break;

      case "+":
      case "-":

        if (valCur.length != 0) {
          // if previous char was not an operator
          if (valCur[valCur.length - 1] != '+' &&
            valCur[valCur.length - 1] != '-' &&
            valCur[valCur.length - 1] != '*' &&
            valCur[valCur.length - 1] != '/') {
            		// decimal		          		
		          	if (valCur[valCur.length-1] == '.') {
								  $("#outputFormula").html(valCur + "0" + valEntered);	
		          	} else {
		          			$("#outputFormula").html(valCur + valEntered);	
		          	}
          } else {
            console.log(valEntered);
            // test if the operator was / or *  , then ok to append.           
            if (valCur[valCur.length - 1] === '*' ||
               valCur[valCur.length - 1] === '/') {
              $("#outputFormula").html(valCur + valEntered);
              break;
            }  
            
            // replace the last operator if there is already one entered.
            
            valCur = valCur.substr(0, valCur.length - 1);
            $("#outputFormula").html(valCur + valEntered);

          }

         } else {
		          if (valEntered === '-') {
		          	$("#outputFormula").html(valEntered);
		          }	
	       }
        break;
      case "÷":
      case "/":
        if (valCur.length != 0) {
          // if previous char was not an operator
          if (valCur[valCur.length - 1] != '+' &&
            valCur[valCur.length - 1] != '-' &&
            valCur[valCur.length - 1] != '*' &&
            valCur[valCur.length - 1] != '/') {
            $("#outputFormula").html(valCur + "/");
          } else {
            var valCurArray = Array.from(valCur);
            var lastOne = valCurArray.pop();
            var lastButOne = valCurArray.slice(valCur.length-2);
            if ( /[+-]/.test(lastOne) && /[\/\*]/.test(lastButOne))
            {           
              valCur = valCur.substr(0, valCur.length - 2);
              $("#outputFormula").html(valCur + "/");
            } else {
              valCur = valCur.substr(0, valCur.length - 1);
              $("#outputFormula").html(valCur + "/");
            }
          }

        };
        break;
      case "x":
      case "*":
        if (valCur.length != 0) {
          if (valCur[valCur.length - 1] != '+' &&
            valCur[valCur.length - 1] != '-' &&
            valCur[valCur.length - 1] != '*' &&
            valCur[valCur.length - 1] != '/') {
            $("#outputFormula").html(valCur + "*");
          } else {
            var valCurArray = Array.from(valCur);
            var lastOne = valCurArray.pop();
            var lastButOne = valCurArray.slice(valCur.length-2);
            if ( /[+-]/.test(lastOne) && /[\/\*]/.test(lastButOne))
            {           
              valCur = valCur.substr(0, valCur.length - 2);
              $("#outputFormula").html(valCur + "*");
            } else {
              valCur = valCur.substr(0, valCur.length - 1);
              $("#outputFormula").html(valCur + "*");
            }
          }
        };
        break;
      case "=":
      case "E":
        // remove leading zeros
        while (valCur.charAt(0) == '0') { // Assume we remove all leading zeros
          if (valCur.length == 1) {
            break
          }; // But not final one.
          if (valCur.charAt(1) == '.') {
            break
          }; // Nor one followed by '.'
          valCur = valCur.substr(1, valCur.length - 1)
        }
        // Resolve expression (round number to avoid dodgy figures)
        if (testExp(valCur)) {
          var resolve = eval(valCur).toFixed(8);
          $("#outputRes").html(parseFloat(resolve));
        }
        $("#outputFormula").html(valCur + "=");
        break;

      default:
        $("#outputFormula").html(valCur);
        break;
    }

  }
});



function testIfHaveOperator (val) { // i.e. the second or later number is being entered - return highest index
	var opIndex = -1;
	var retVar = false;
	if (val.lastIndexOf('+') > -1 && val.lastIndexOf('+') > opIndex) opIndex = val.lastIndexOf('+');
	if (val.lastIndexOf('-') > -1 && val.lastIndexOf('-') > opIndex) opIndex = val.lastIndexOf('-');
	if (val.lastIndexOf('*') > -1 && val.lastIndexOf('*') > opIndex) opIndex = val.lastIndexOf('*');
	if (val.lastIndexOf('/') > -1 && val.lastIndexOf('/') > opIndex) opIndex = val.lastIndexOf('/');
	//(opIndex > -1) ? retVar = opIndex : retVar = false;
	return opIndex;
}
	

function testExp(expr) {
  // test for mathematical expression
  var regEx = new RegExp("^([-+/*]\d+(\.\d+)?)*");
  return regEx.test(expr);
}

function testNum(numChar) {
  // test for mathematical expression
  var num = parseInt(numChar);
  return !isNaN(num);
}

function testMathFunc(ch) {
  // test for mathematical function
  var regEx = new RegExp("^[-]|[+]");
  return regEx.test(ch);
}

function checkExpression(xprAll) {
  var xpr = xprAll.split('');
  var leadingMinus = false;
  var pos = 0;
  // test for a leading operator
  if (xpr[0] == '-') leadingMinus = true;
  if (xpr[0] == '+') xpr.shift(); // ignore and remove

  for (var i = pos; i < xpr.length; i++) {
    switch (xpr[i]) {
      case '+':
      case '-':
      case '/':
      case '*':
        xpr[i] = 'r';
        break;
    }
  }
  var valid = true;
  var xprStr = xpr.join('');
  if (leadingMinus) {
    xprStr = xprStr.substr(1, xprStr.length - 1);
    if (isNaN(parseFloat(xprStr))) {
      valid = false;
    } else {
      xprStr = "-" + xprStr;
    }

  } else {
    if (isNaN(parseFloat(xprStr)))
      valid = false;
  }
  var parts = xprStr.split('r');
  var lastPart = parts[parts.length - 1];
  for (let number of parts) {
    if (isNaN(parseFloat(number))) valid = false;
  }
  var countDots = 0;
  for (var idx = 0; idx < lastPart.length; idx++) {
    if (lastPart[idx] === '.') countDots++;
    if (countDots > 0) valid = false;
  }
  return valid;
}
  
              
            
!
999px

Console