HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs 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 its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div class="container">
<div class="message">
<h1>Simple React Calculator</h1>
<p><strong>Continous calculation</strong> and <strong>keyboard inputs</strong> are working. Esc is <strong>AC</strong>, Enter does not execute, but does <strong>'click' on focused button</strong>.</p>
</div>
<div class="calculator">
<div id="root"></div>
</div>
</div>
$font-family: 'Roboto', sans-serif;
$white: #ffffff;
$grey20: #f9f9f9;
$grey80: #555555;
$grey40: #333;
$gradient-orange: linear-gradient(0.35turn, #FBAB7E, #F7CE68);
body {
font-family: $font-family;
height: 100vh;
min-height: 800px;
background: $grey40;
overflow: auto;
}
button {
background: $white;
color: $grey80;
font-family: $font-family;
font-size: 16px;
border: none;
padding: 15px;
flex-grow: 1;
width: 50px;
&:focus {
outline: none;
}
}
.message {
text-align: center;
color: $white;
margin-bottom: 30px;
min-width: 300px;
max-width: 40%;
h1 {
font-family: 'Roboto Slab';
font-size: 2rem;
margin-bottom: 20px;
line-height: 2.5rem;
}
p {
font-size: 0.8rem;
line-height: 1.2rem;
}
strong {
font-weight: bold;
}
}
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.calculator {
border-radius: 7px;
overflow: hidden;
box-shadow: 0 0 50px #202020;
}
.display {
font-size: 3rem;
font-weight: 300;
padding: 20px 10px;
color: $white;
background: $gradient-orange;
&-text {
flex-grow: 5;
text-align: right;
}
&-overall {
font-size: 12px;
line-height: 10px;
height: 20px;
margin-bottom: 10px;
color: rgba(255,255,255,0.6);
}
}
.row {
display: flex;
}
.inputs {
display: flex;
}
.sides {
display: flex;
flex-direction: column;
.ac {
flex-grow: 1;
}
.equal {
flex-grow: 2;
color: $white;
background: $gradient-orange;
}
}
.operator,
.sides {
button {
background: $grey20;
}
}
.operator button {
&.active {
background: $gradient-orange;
color: $white;
}
}
class CalcApp extends React.Component {
state = {
firstVal: '',
secondVal: '',
operator: '',
display: '0',
}
componentDidMount() {
const { keypressHandler } = this
document.addEventListener('keyup', ev => {
keypressHandler(ev)
})
}
keypressHandler = ev => {
const {
setNumberValue,
setOperatorValue,
equalHandler,
allClear,
deleteChar,
} = this
const {
operator,
secondVal,
} = this.state
const numRegex = /^([0-9]|\.)*$/g;
const opRegex = /[+|\-|:|*]/g;
const eqRegex = /(=)/g;
const delRegex = /(Backspace|Delete)/g;
const acRegex = /(Escape)/g;
const key = ev.key
const isNumber = !!numRegex.exec(key)
const isOperator = !!opRegex.exec(key)
const isEqual = !!eqRegex.exec(key)
const isDel = !!delRegex.exec(key)
const isAc = !!acRegex.exec(key)
if (key && isNumber) {
setNumberValue(key + '')
}
if (key && isOperator) {
setOperatorValue(key + '')
}
if (key && isEqual) {
equalHandler()
}
if (key && isDel) {
deleteChar()
}
if (key && isAc) {
allClear()
}
}
resetState = resetAll => {
if (resetAll) {
this.setState({
firstVal: '',
secondVal: '',
operator: '',
display: '0',
})
} else {
this.setState({
firstVal: '',
secondVal: '',
operator: '',
})
}
}
hasPoint = (value) => {
return value.indexOf('.') > -1
}
setNumberValue = value => {
const {
firstVal,
secondVal,
operator,
} = this.state
const {
fixNumberString,
setDisplay,
} = this
let total
// if point is pressed, check if we already have it in current states
if (value === '.') {
if (!operator && !this.hasPoint(firstVal)) {
total = fixNumberString(firstVal + value)
this.setState({
firstVal: total
})
}
if (!!operator && !this.hasPoint(secondVal)) {
total = fixNumberString(secondVal + value)
this.setState({
secondVal: total
})
}
if (total) {
setDisplay(total + '')
}
return
}
// if input is a number, check if it's first or second number
if (!operator) {
total = fixNumberString(firstVal + value)
this.setState({
firstVal: total
})
} else {
total = fixNumberString(secondVal + value)
this.setState({
secondVal: total
})
}
setDisplay(total + '')
}
getOverall = () => {
const {
firstVal,
secondVal,
operator,
} = this.state
return firstVal + ' ' + operator + ' ' + secondVal
}
setDisplay = value => {
const {
firstVal,
secondVal,
} = this.state
this.setState({
display: value,
})
}
getCurrentTargetValue = () => {
const {
firstVal,
secondVal,
operator,
} = this.state
return !operator ? firstVal : secondVal
}
numberClickHandler = (e) => {
const value = e.target.innerHTML
if (value) {
this.setNumberValue(value)
}
}
setOperatorValue = operatorInput => {
const {
firstVal,
secondVal,
operator,
display,
} = this.state
const {
fixNumberString,
calculate,
setDisplay,
} = this
const fixedNumber = fixNumberString(firstVal, false)
if (firstVal && !secondVal) {
this.setState({
operator: operatorInput,
display: fixedNumber,
})
} else if (firstVal && operator && secondVal) {
const total = calculate()
this.setState({
operator: operatorInput,
firstVal: total + '',
secondVal: '',
})
setDisplay(total + '')
} else {
this.setState({
operator: operatorInput,
firstVal: fixNumberString(display, false),
})
}
}
operatorClickHandler = (e) => {
const { setOperatorValue } = this
const operatorInput = e.target.innerHTML
setOperatorValue(operatorInput)
}
allClear = () => {
this.resetState(true)
}
deleteChar = () => {
const {
firstVal,
secondVal,
operator,
} = this.state
const opRegex = /[+|\-|:|*]/g;
if (!operator) {
const newVal = firstVal.slice(0, -1)
this.setState({
firstVal: newVal,
display: newVal ? newVal : '0',
})
} else if (operator && !secondVal) {
this.setState({
display: firstVal,
operator: '',
})
} else {
const newVal = secondVal.slice(0, -1)
this.setState({
secondVal: newVal,
display: newVal ? newVal : '0',
})
}
}
removeZeroAtStart = value => {
return value.indexOf('0') === 0 ? value.substring(1) : value
}
fixNumberString = (value, finalize = false) => {
// if input has hanging point e.g. '0.'/'1.', add trailing zero
// should only run when moving to second value / begin calculation
if (finalize && value.indexOf('.') === value.length - 1 && value.length > 1) {
return value + '0'
}
// if value has zero prefix but not a decimal value, e.g. '01'/'03', remove zero
if (value.indexOf('0') === 0 && !value.indexOf('0.') === 0) {
return value.substring(1)
}
// if value is a first point input '.', add zero prefix
if (value.indexOf('.') === 0 && value.length === 1) {
return '0.'
}
if (!value) {
return '0'
}
return value
}
calculate = () => {
const {
firstVal,
secondVal,
operator,
} = this.state
const {
fixNumberString,
} = this
const vfirstVal = fixNumberString(firstVal, true)
const vsecondVal = fixNumberString(secondVal, true)
let total = '0';
switch (operator) {
case '-' :
total = parseFloat(vfirstVal) - parseFloat(vsecondVal)
break;
case '*':
total = parseFloat(vfirstVal) * parseFloat(vsecondVal)
break;
case ':' :
total = parseFloat(vfirstVal) / parseFloat(vsecondVal)
break;
case '+' :
default:
total = parseFloat(vfirstVal) + parseFloat(vsecondVal)
break;
}
return total.toLocaleString()
}
equalHandler = () => {
const {
firstVal,
secondVal,
operator,
} = this.state
const {
setDisplay,
resetState,
calculate,
} = this
if (firstVal && secondVal && operator) {
let total = calculate()
setDisplay(total + '')
resetState()
}
}
render() {
const {
display,
operator,
} = this.state
const {
operatorClickHandler,
numberClickHandler,
deleteChar,
allClear,
equalHandler,
getOverall,
} = this
const activeOperator = name => {
return operator === name ? 'active' : ''
}
return (
<div>
<div className="display">
<p className="display-overall">{ getOverall().trim() }</p>
<p className="display-text">{ display }</p>
</div>
<div className="inputs">
<div className="column main">
<div className="operator">
<div className="row">
<button
className={activeOperator('+')}
onClick={operatorClickHandler}>+</button>
<button
className={activeOperator('-')}
onClick={operatorClickHandler}>-</button>
<button
className={activeOperator(':')}
onClick={operatorClickHandler}>:</button>
<button
className={activeOperator('*')}
onClick={operatorClickHandler}>*</button>
</div>
</div> { /* operator */ }
<div className="numbers">
<div className="row">
<button onClick={numberClickHandler}>1</button>
<button onClick={numberClickHandler}>2</button>
<button onClick={numberClickHandler}>3</button>
</div>
<div className="row">
<button onClick={numberClickHandler}>4</button>
<button onClick={numberClickHandler}>5</button>
<button onClick={numberClickHandler}>6</button>
</div>
<div className="row">
<button onClick={numberClickHandler}>7</button>
<button onClick={numberClickHandler}>8</button>
<button onClick={numberClickHandler}>9</button>
</div>
<div className="row">
<button onClick={numberClickHandler}>.</button>
<button onClick={numberClickHandler}>0</button>
<button onClick={deleteChar}>C</button>
</div>
</div> { /* numbers */ }
</div> { /* main */ }
<div className="column sides">
<button className="ac" onClick={allClear}>AC</button>
<button className="equal" onClick={equalHandler}>=</button>
</div> { /* sides */ }
</div> { /* inputs */ }
</div>
)
}
}
ReactDOM.render(
<CalcApp />,
document.getElementById('root')
);
Also see: Tab Triggers