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

              
                <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>

<!-- Google Fonts: -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Hind:wght@300;400;500&display=swap" rel="stylesheet">

<div id="root" class="wrapper">
  
<div>
  
  
              
            
!

CSS

              
                // ***************************************
// Base
// ***************************************
*,
*::before,
*::after{
  margin:0px;
  padding:0px;
  box-sizing: border-box;
}

html{
  font-size:62.5%;
}
html,
body{
    margin: 0px;
    padding: 0px;

    min-width: 100%;
    width: 100vw;
    max-width: 100%;

    min-height: 100%;
    height: 100vh;
    max-width: 100%;

    overflow: auto;
}

body{
  font-size:1.6rem;
  font-weight: 300;
  font-family: 'Hind', sans-serif;
  
}

button,
label{
  cursor : pointer;
}


// ***************************************
// Style:
// ***************************************

.wrapper{
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.claculator{

  box-shadow: 0px 6px 13px -5px #a5a3a3;
  border-radius: .5rem;
  
  overflow: hidden;
  &__screen{
    width: 100%;
    height: 8rem;
  }
  &__keyboard{
    
  }
}

.screen{
  padding: 0rem 1rem;
  background-color: #6A6969;
  
  
  &__data{
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #6A6969;
    border: none;
    outline: none;
    
    font-size: 2rem;
    color: #fff;
    font-weight: 300; 
    
    /* Chrome, Safari, Edge, Opera */
    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }

    /* Firefox */
    input[type=number] {
      -moz-appearance: textfield;
    }
  }
}

.keyboard{
  display: grid;
  grid-template-columns: repeat(4, calc(6rem - .5rem));
  grid-template-rows: repeat(5,calc(5rem - .6rem));
  gap: .1rem;
  grid-template-areas: 
    "ac perc divide multiply"
    "seven eight nine subtract"
    "four five six add"
    "one two three equals"
    "zero zero decimal equals";
  
    background-color: #707070;
  
  &__button{
      background-color: #939292;
      border: none;
      color: white;
      outline: none;
    
      &:active{ background-color: darken(#939292, 10%); }
    
      &_clear,
      &_perc,
      &_divide{
        background-color: #7B7B7B;
        
        &:active{ background-color: darken(#7B7B7B, 10%); }
      }
      
      &_multiply,
      &_subtract,
      &_add,
      &_equals{
        background-color: #FDAA49;
         
        &:active{ background-color: darken(#FDAA49, 10%); }
      }
  }
}

.selected{
  border : 1px solid black;  
}

#clear{     grid-area: ac;  }
#perc{      grid-area: perc;}
#divide{    grid-area: divide;}
#multiply{  grid-area: multiply;}
#subtract{  grid-area: subtract;}
#add{       grid-area: add;}
#equals{    grid-area: equals;}
#nine{      grid-area: nine;}
#eight{     grid-area: eight;}
#seven{     grid-area: seven;}
#six{       grid-area: six;}
#five{      grid-area: five;}
#four{      grid-area: four;}
#three{     grid-area: three;}
#two{       grid-area: two;}
#one{       grid-area: one;}
#zero{      grid-area: zero;}
#decimal{   grid-area: decimal;}
              
            
!

JS

              
                
const buttons = [
    {
      name : 'AC',
      id : 'clear',
      style : 'keyboard__button_clear',
      key : 'AC'
    },
    {
      name : '%',
      id : 'perc',
      style : 'keyboard__button_perc',
      key : '%'
    },
    {
      name : '/',
      id : 'divide',
      style : 'keyboard__button_divide',
      key : '/'
    },
    {
      name : 'x',
      id : 'multiply',
      style : 'keyboard__button_multiply',
      key : '*'
    },
    {
      name : '-',
      id : 'subtract',
      style : 'keyboard__button_subtract',
      key : '-'
    },
    {
      name : '+',
      id : 'add',
      style : 'keyboard__button_add',
      key : '+'
    },
    {
      name : '=',
      id : 'equals',
      style : 'keyboard__button_equals',
      key : '='
    },
    {
      name : 9,
      id : 'nine',
      style : '',
      key : '9'
    },
    {
      name : 8,
      id : 'eight',
      style : '',
      key : '8'
    },
    {
      name : 7,
      id : 'seven',
      style : '',
      key : '7'
    },
    {
      name : 6,
      id : 'six',
      style : '',
      key : '6'
    },
    {
      name : 5,
      id : 'five',
      style : '',
      key : '5'
    },
    {
      name : 4,
      id : 'four',
      style : '',
      key : '4'
    },
    {
      name : 3,
      id : 'three',
      style : '',
      key : '3'
    },
    {
      name : 2,
      id : 'two',
      style : '',
      key : '2'
    },
    {
      name : 1,
      id : 'one',
      style : '',
      key : '1'
    },
    {
      name : 0,
      id : 'zero',
      style : '',
      key : '0'
    },
    {
      name : '.',
      id : 'decimal',
      style : '',
      key : '.'
    }
  ]
 

// TO Do:
/*
 X 1 Clicable element should contane id='equals';
 X 9 Clicable that contains the ids = id="zero", id="one", id="two", id="three", id="four", id="five", id="six", id="seven", id="eight", and id="nine";
 X 4 Clickble elements with the ids = id="add", id="subtract", id="multiply", id="divide"
 X 1 Clickable element with the id = "decimal" and containe '.';
 X 1 Clickable element that contains tghe id = 'clear';
 X 1 element with id = "display"" that display values;
 
 X Any Time pressing "Clear" clears the INPUT's and OUTPUT's values and return the calculator to initial state. 
   0 should be inside an element with id = "display";
 X As I input numbers I should be able to see my INPUT in the element with id = 'display';
 X In any order I should add, subtrack, multiply and divide chain of of any length, when I hit '=' button the corrisponding result should shown in an element with id = "display";
 X When inputing multiple numbers, my calculator should no't allo myltiple 00 at the begining;
 X When hit '.' should add to number and prevent multiple '..';
 X I should perform any math operation (*,/,-,+) in any order on numbers containing decimal points;
 X If two or more operators are entered consequitively, the operation performed should be the last operator entered (excluding negative sign (-)).
    For exmp = 5 * + 7 = 35, if 5 * - 5 = -25;
 X Pressing an operator '=', should perform new calculation with previous result;
 X My calculator should have several decimal places of precision when it comes to rounding (note that there is no exact standard, but you should be able to handle calculations like 2 / 7 with reasonable precision to at least 4 decimal places). 
*/

const getMathResult = {
    '/':(bufferVal,currentVal) => bufferVal /= currentVal,
    '*':(bufferVal, currentVal) => bufferVal *= currentVal,
    '-':(bufferVal, currentVal) => bufferVal -= currentVal,
    '+':(bufferVal, currentVal) => bufferVal += currentVal,
    '=':(bufferVal, currentVal) => bufferVal,
}




function Keyboard ({output}) {
  
  const [underlinedOperator, setUnderlinedOperator] = React.useState(null);
  
  const prev = React.useRef('');
  const input = React.useRef('');
  const buffer = React.useRef(0);
  
  
  // **************************************************
  
  
  const getButton = (key) => {
    // Handle Numbers and dot
    if(/[0-9|\.]/.test(key)){
      handleNumbers(key);
    }
    
    // Handle Operators
    if(/[\/\*\-\+]/.test(key)){
      handleOperators(key);
    }
    
    // Handle Equal
    if(key == '='){
      handleEqual(key);
    }
    
    // Handle Reset
    if(key === 'AC'){
      reset();
    }
  }
  
  
  // **************************************************
  
  const reset = () => {
    output('0');
    buffer.current = 0;
    input.current = '';
    prev.current = ''
    setUnderlinedOperator(null);
  }
  
  const handleNumbers = (n) => {
    // Display Numbers typing
    
    // Multiple Zero controller:
    if(n == '0' && input.current.length == 0) return;
    
    // Multiple period controller:
    if(input.current.includes('.') && n == '.') return;
    
    output(input.current += n);
  }
  
  const handleEqual = (equal) => {
    let sum;
      
      if(/[\/\*\-\+]/.test(prev.current) && underlinedOperator === '-'){
        sum = getMathResult[prev.current](buffer.current, Number(-input.current));       
      }
      else{
        sum = getMathResult[underlinedOperator](buffer.current, Number(input.current));       
      }

      output(sum);
      buffer.current = sum;
      input.current = '';
      prev.current = '';
  }
  
  const handleOperators = (operator) => {
    
      // Underline Current Operator
      setUnderlinedOperator(operator);  
    
      // Does Math  based on Previous operator, buffer value val and current number value
      if(underlinedOperator && input.current){

          const sum = getMathResult[underlinedOperator](buffer.current, Number(input.current)); 
          // display claculated value don the screen:
          output(sum);
          
          buffer.current = sum;
          input.current = ''; 
      }
      // define buffer value when operator is clicked for the first time
      else{
        buffer.current += Number(input.current);
        input.current = '';
      }
    
      
     // Define Previously selected operator:
      prev.current = underlinedOperator;
  }
  
  
  // **************************************************

  return (
    <main class="claculator__keyboard keyboard">
          {buttons.map(button => {
            return (
              <button 
                key={button.key}
                id={button.id} 
                type="button" 
                name={button.key} 
                className={`keyboard__button ${button.style} ${underlinedOperator == button.key ? 'selected' : ''}`}
                onClick={(event) => getButton(event.target.name)}
                >
                {button.name}
              </button>
            )
          })}
   </main>
  )
};


 function Screen ({sum}){
   
   return (
     <header  class="claculator__screen screen">
         <div id="display" className="screen__data" >{sum}</div>
     </header>
   )
 }

  
  
  function Calculator () {
    const [output, setOutput] = React.useState('0');
    
    const getInput = (n) => setOutput(n);

    return (
      <div class="claculator">
        <Screen sum={output}/>
        <Keyboard output={getInput}/>
      </div>
    )
  }
  
  ReactDOM.render(<Calculator />, document.getElementById('root'));




              
            
!
999px

Console