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.

Details

Privacy

Go PRO Window blinds lowered to protect code. Code Editor with window blinds (raised) and a light blub turned on.

Keep it secret; keep it safe.

Private Pens are hidden everywhere on CodePen, except to you. You can still share them and other people can see them, they just can't find them through searching or browsing.

Upgrade to PRO

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.

Template

Make Template?

Templates are Pens that can be used to start other Pens quickly from the create menu. The new Pen will copy all the code and settings from the template and make a new Pen (that is not a fork). You can view all of your templates, or learn more in the documentation.

Screenshot

Screenshot or Custom Thumbnail

Screenshots of Pens are shown in mobile browsers, RSS feeds, to users who chose images instead of iframes, and in social media sharing.

This Pen is using the default Screenshot, generated by CodePen. Upgrade to PRO to upload your own thumbnail that will be displayed on previews of this pen throughout the site and when sharing to social media.

Upgrade to PRO

HTML

              
                <html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>My first calculator</title>
    <link href="https://fonts.googleapis.com/css2?family=Electrolize&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>

<body>

    <h2>My first Calc<span style="color: #FFAA00">ulator</span></h2>

    <div class="calculator">

        <div class="text-input">
                
        <span id="input"></span>

        </div>
            
        <div class="calculator-box">

        <button class="on">ON</button>
        <button class="off">OFF</button>
        <button class="delete-last-character"></button>
        <button class="operator"></button>
        <button class="delete-all-character">DEL</button>

        <button class="number">7</button>
        <button class="number">8</button>
        <button class="number">9</button>

        <button class="operator">×</button>
        <button class="operator">a <sup>x</sup></button>

        <button class="number">4</button>
        <button class="number">5</button>
        <button class="number">6</button>

        <button class="operator">+</button>
        <button class="operator">/</button>

        <button class="number">1</button>
        <button class="number">2</button>
        <button class="number">3</button>

        <button class="operator">-</button>

        <button class="number">0</button>
        <button class="operator">.</button>
        <button class="operator">%</button>

        <button class="result">=</button>

        </div>
    </div>

    <footer></footer>

</body>
<script src="https://husdady.github.io/derechos-de-autor/copyrigth.js"></script>
<script>
	loadHTML("footer", 0);
</script>
</html>
              
            
!

CSS

              
                body{
background: rgb(23,125,173);
background: linear-gradient(0deg, rgba(23,125,173,1) 0%, rgba(0,0,0,1) 100%);
background-repeat: no-repeat;
margin: 0;
padding: 0;
font-size: 18px;
}
html, body{
display: table;
width: 100%;
}
h2{
font-size: 2.25em;
text-align: center;
margin: 40px 0;
font-family: 'Electrolize', sans-serif;
color: azure;
}
.calculator{
width: 100%;
max-width: 350px;
margin: auto;
background: rgb(0,0,0);
background: linear-gradient(0deg, rgba(0,0,0,0.85) 2%, rgba(4,59,121,0.3) 60%, rgba(0,0,0,0.2) 85%);
height: 450px;
box-sizing: border-box;
padding-top: 30px;
margin-bottom: 50px;
border-radius: 25px;
box-shadow: 10px 10px 20px 4px rgba(0,0,0,0.25);
border: 1px solid rgba(240, 255, 255, 0.25);
}
.text-input{
max-width: 300px;
width: 100%;
margin: auto;
border-radius: 15px;
border-top: 4px solid rgba(0,0,0,0.5); 
border-left: 4px solid rgba(0,0,0,0.5);
height: 50px;
line-height: 2.5;
padding: 0 15px;
box-sizing: border-box;
background: rgba(255,255,255,0.75);
font-weight: bold;
font-size: 18px;
font-family: 'Electrolize', system-ui, sans-serif;
}
#input{
display: block;
white-space: nowrap;
overflow: hidden;
text-align: right;
}
#input > sup{
font-size: 60%;
}
.calculator-box{
width: 100%;
max-width: 300px;
margin: 5% auto 5% auto;
display: grid;
grid-template-columns: auto auto auto auto;
grid-gap: 10px;
}
button{
color: white;
font-weight: bold;
padding: 10px;
border-radius: 6px;
text-align: center;
font-family: 'Electrolize', system-ui, sans-serif;
border: none;
box-shadow: 0px 4px 0px 0px rgba(255,255,255,0.45);
}
button:hover{
cursor: pointer;
}
button:focus,
#input:focus{
outline: none;
}
button:active{
transform: scale(0.85);
}
button:disabled{
opacity: 0.6;
}
.operator{
background: rgba(0,0,0,0.45);
font-size: 0.95em;
}
.number{
background: rgba(255,255,255,0.75);
color: black;
font-size: 1.05em;
}
.delete-all-character{
background: darkred;
}
.result{
background: rgba(255,170,0,0.8);
color: black;
font-size: 1.25em;
grid-column: 4/6;
grid-row: 5;
}
.on,
.off{
background: rgba(255,255,255,0.75);
color: black;
}
.delete-last-character{
background: dimgrey;
}
.delete-last-character:before{
content: "\f55a";
}
button:nth-child(4):before{
content: "\f698";
}
.delete-last-character:before,
button:nth-child(4):before{
font-family: "Font Awesome 5 Pro";
font-weight: 400;
}
button:nth-child(14){
grid-column: 4;
grid-row: 3/5;
}
.active{
background: black;
color: white;
}
              
            
!

JS

              
                /* My First Calculator */

/* Mi primera calculadora sin hacer uso de eval() 
Para poder calcular he usado expresiones regulares para hacer un filtro
de busqueda avanzado sobre el posicionamiento de numeros y operadores a
calcular. He comantado el codigo en español, no solo para mejorar su lectura
sino para no olvidarme en un futuro de las cosas que hace
*/

document.addEventListener('DOMContentLoaded', ()=>{

/* Selectores */
const textInput = document.getElementById('input'),
      box = document.querySelector('.calculator-box'),
      buttonOn = document.querySelector('.on'),
      buttonOff = document.querySelector('.off'),
      buttonAll = document.querySelectorAll('button');

// Agregar clase active a boton con clase "on"
buttonOn.classList.add('active');
valueDefault();

// Limpiamos todo el valor de entrada de la calculadora
const cleanCalculator = () =>{
textInput.textContent = '';
};


// Igualar a 0
function valueDefault(){
textInput.textContent = "0";
}

// Eliminar ultimo caracter
function removeLastCharacter(z){
z.innerHTML = z.innerHTML.slice(0, -1);
}

// Eliminar ultimo caracter
const deleteLastCharacter = y =>{
let lastSupTag = textInput.querySelector("sup:last-child"),
    selectLastTagSup = /<sup>.+<\/sup>$/gim;

if (textInput.contains(lastSupTag)){ /*
Si identificador input contiene un sup al final del contexto */

selectLastTagSup.test(textInput.innerHTML) 
/* Si hay una etiqueta sup al final y despues no hay numeros o signos
eliminar numeros en la etiqueta sup */
? removeLastCharacter(lastSupTag) 
: null // No hagas nada

lastSupTag.innerHTML === "" /* Si el contenido de la etiqueta sup 
esta vacio, eliminame la etiqueta sup, esta no se elimina automaticamente*/
? lastSupTag.remove()
: removeLastCharacter(y) /* de lo contrario primero elimina el texto que
esta despues*/

}

else {

    y.textContent.length === 1 /* Si en el contenido del input solo hay
    una caracter, al volver hacer click en el boton, igualame a 0 */
    ? valueDefault()
    : removeLastCharacter(y) /* De lo contrario, eliminame el ultimo caracter*/

}

    }


// Agregar caracteres a input
const addCharacter = (character, elementParent) =>{

if (elementParent.innerHTML == "0" || elementParent.innerHTML == "x"){
elementParent.innerHTML = character; // Igualar texto al texto del parametro text
} else {
elementParent.innerHTML += character;  // Concatenar texto al texto del parametro text
textInput.scrollLeft += 20;
}

    }


let statusPower = true; // La usaremos luego para validar cosas

// Condicion para agregar numeros
const addNumber = number =>{

    let lastSupTag = textInput.querySelector('sup:last-child');

    if (textInput.contains(lastSupTag)){ /* Si input contiene una etiqueta
    sup al final */

    lastSupTag.innerHTML === "x" /* Si el contexto de la etiqueta sup es
    igual a x cambiamelo por el numero, si no es x concatena numeros*/
    ? addCharacter(number, lastSupTag)
    : statusPower == true /* si es true, concatename en etiqueta sup */
        ? addCharacter(number, lastSupTag)
        : addCharacter(number, textInput) /* si es false, concatename
        fuera de la etiqueta sup */

    }

    else {

    addCharacter(number, textInput); /* si no contiene etiquetas sup
    agregar numeros fuera de esta etiqueta */
    justOneExponent = true;    /* cambiamos a true para volver a escribir
    etiquetas sup */

    }

}


let justOneExponent = true; // La usaremos luego para validar cosas

// Condicion para agregar operadores
const addOperator = operator =>{

    if (operator.includes("a")){

    let newSup = document.createElement("sup"),
          newTextSup = document.createTextNode("x");

         newSup.appendChild(newTextSup);

         statusPower = true;

         // si es true agregame una tag <sup>
         if (justOneExponent === true) textInput.appendChild(newSup)

         textInput.scrollLeft += 20; // Para mantener el ultimo numero y no perder focus

         justOneExponent = false; // cambia a false para ya no agregar etiquetas sup


    } else {

        addCharacter(operator, textInput); // concatenar operadores
        statusPower = false; /* cambiando a false para dejar de escribir en <sup>
        y escribir fuera de esta */
        justOneExponent = true; // cambiando a true para volver a agregar <sup>

    }
    
}


// Evento click para agregar el signo de raiz
buttonAll[3].addEventListener('click', () =>{

let tokenRoot = `√`;
 if (textInput.innerHTML === "0"){
textInput.innerHTML = tokenRoot;
} else {
textInput.innerHTML += tokenRoot;
}

})

// Evento click en boton con clase "on"
const activeCalculator = () =>{

buttonOff.classList.remove('active'); // Agregar clase
buttonOn.classList.add('active'); // Remover clase
valueDefault(); // Valor de input igual a 0

for(let i=0; i<buttonAll.length; i++){
    buttonAll[i].removeAttribute('disabled');
    // Remover todos los atributos disabled en todos los botones  
}

    }


// Evento click en boton Off
const desactiveCalculator = () =>{

buttonOn.classList.remove('active'); // Remover clase
buttonOff.classList.add('active'); // Agregar clase

for(let i=0; i<buttonAll.length; i++){
    if(buttonAll[i].className !== 'on' && buttonAll[i].className !== 'off active'){
    buttonAll[i].disabled = "true"; /* Agregar atributo disabled solo a
    botones que no tengan la clase "on" ni "off" */
    }
}

    }


/* Evento click en el calculator-box para luego seleccionar cada boton
dependiendo de su contexto */ 
box.addEventListener('click', e =>{

    let target = e.target;

    if (target.className === "on"){

        return activeCalculator();

    }

    else if (target.className === "off") {

        desactiveCalculator();
        return cleanCalculator();

    }

    else if (target.className === "delete-last-character"){

        return deleteLastCharacter(textInput);

    }

    else if (target.className === "delete-all-character"){

        return valueDefault();

    }

    else if (target.className === "number"){
        
        return addNumber(target.innerHTML);

    }

    else if (target.className === "operator"){

        return addOperator(target.innerHTML);

    }

    else if (target.className === "result"){

        justOneExponent = true;
        return textInput.innerHTML = calculate(textInput.innerHTML);

    }    

})

/* Necesitas saber expresiones regulares para entender esto,
no se si es la mejor forma de hacerlo, puede que hayan otras mejores
formas de reducir las siguientes expresiones regulares*/
const calculate = operation =>{

    // output 3√9 = 9
    let multiplication_root = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))\√((?:\d+)?[\.]?(?:\d+|\Infinity))/,
    // output √9 = 3
    root = /\√((?:\d+)?[\.]?(?:\d+|\Infinity))/,
    // output 3² = 9
    power = /((?:\-)?(?:\d+)?[\.]?(?:\d+|Infinity))<sup>(\d+)<\/sup>/,
    // output 9/3 = 3
    division = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))\/((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity)(?:\.\d+)?)/,
    // output 9×3 = 27
    multiplication = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))\×((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity)(?:\.\d+)?)/, 
    // output 9%3 = 0 
    modulus = /((?:\d+)?[\.]?(?:\d+|\Infinity))\%((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity)(?:\.\d+)?)/,
    // output 9+3 = 12
    sum = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))\+([\.]?(?:\d+|\Infinity)(?:\.\d+)?)/,
    // output 9-3 = 6
    subtraction = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))\-([\.]?(?:\d+|\Infinity)(?:\.\d+)?)/,
    // output 3% = 0.03
    percentage = /((?:\-)?(?:\d+)?[\.]?(\d+))\%(?!\d+|\b$)/g,
    // output 4+2% = 4.08 
    percentageOperation = /((?:\-)?(?:\d+)?[\.]?(?:\d+|\Infinity))(\+|\-)([\.]?(?:\d+|\Infinity)(?:\.\d+)?)\%(?!\d+|\b$)/,
    // En caso de que haya +- cambiarlo por +
    conditionMinus = /\+\-|\-\+/,
    // En caso de que haya -- cambiarlo por -
    conditionPlus = /\-\-|\+\+/,
    // En caso de que haya .2 cambiarlo por 0.2
    decimalNumbers = /^(\.)(\d+)/;

    let newExpr;

    if (decimalNumbers.test(operation)){

    operation = operation.replace(decimalNumbers, (match, point, number)=>{

    return "0" + point + number

    })

       }
       
    else if (conditionMinus.test(operation)){

        operation = operation.replace(conditionMinus, "-");

        }

        else if (conditionPlus.test(operation)){

        operation = operation.replace(conditionPlus, "+");

        }
       

    // Si no es numero, es decir, string, booleano, null, undefined
    if (isNaN(operation)){

    /* Comprobara cada una de las expresiones regulares, reemplazara
    y ejecutara su operacion en la pantalla*/ 

        if (power.test(operation)){

        newExpr = operation.replace(power, (match, a, b)=>{

        return Math.pow(+a, +b);

        })

        }

        else if (multiplication_root.test(operation)){

        newExpr = operation.replace(multiplication_root, (match, a, b)=>{
    
        return +a * Math.sqrt(+b);
    
        })
    
        }

        
        else if (root.test(operation)){

        newExpr = operation.replace(root, (match, a)=>{
    
        return Math.sqrt(+a);
    
        })
    
        }
            
        else if (percentageOperation.test(operation)){

        newExpr = operation.replace(percentageOperation, (match, a, b, c)=>{
        return +a + b + (+a * +c) / 100;

        })

        }

        else if (percentage.test(operation)){

        newExpr = operation.replace(percentage, (match, a)=>{

        return +a / 100;
    
        })
    
        }
      

        else if (division.test(operation)){

        newExpr = operation.replace(division, (match, a, b)=> {
    
        if(b != 0){
        return +a / +b;
        }
        else{
        return operation = "0";
        }

        });

        }


        else if (multiplication.test(operation)){

        newExpr = operation.replace(multiplication, (match, a, b)=>{

        return +a * +b;

       	});

        } 


        else if (modulus.test(operation)){

            newExpr = operation.replace(modulus, (match, a, b)=>{
            
            function mod(n, m) {
            return ((n % m) + m)  % m;
            }
                    
            return mod(+a, +b);
                    
            });
                    
            }
        

       	else if (subtraction.test(operation)){

        newExpr = operation.replace(subtraction, (match, a, b)=>{

        return +a - +b;

        });

        }


        else if (sum.test(operation)){

        newExpr = operation.replace(sum, (match, a, b)=>{

        return +a + +b;

        });

        }


        else if (operation === "Infinity"){

        return operation = "Infinity"

        }

        else if (operation === "NaN"){
       
        return operation = "0"
       
        }

        else {
           
        return operation = "Syntax Error!";

        }


       	return calculate(newExpr);


        }


    else {

    return operation;

    }    
}

});
              
            
!
999px
If a groundhog inspects their Web Component, do they see their Shadow DOM?

Console