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.
const INITIAL_FONTS = ['Asset', 'Bevan', 'Inconsolata', 'Rubik Beastly'];
// Default: val * i.
const FNS = {
translateY: (n, i) => n * (Math.sqrt(i) - 1),
scaleX: (n, i) => Math.pow(i, n),
scaleY: (n, i) => Math.pow(i, n),
};
async function getLocalFonts() {
try {
if ('queryLocalFonts' in window) {
const localFonts = await window.queryLocalFonts();
return localFonts.map(fontData => ({
postscriptName: fontData.postscriptName,
fullName: fontData.fullName,
family: fontData.family,
style: fontData.style,
}));
} else return [];
} catch (err) {
return [];
}
}
const App = React.createClass({
getInitialState() {
return {
closed: false,
page: 1,
fields: {
functions: {
translateX: {
type: 'number',
value: 0,
},
translateY: {
type: 'number',
value: 42,
},
scaleX: {
step: 0.1,
type: 'number',
units: ' ',
value: -0.4,
},
scaleY: {
step: 0.1,
type: 'number',
units: ' ',
value: -0.6,
},
rotate: {
type: 'number',
units: 'deg',
value: 0,
},
skewX: {
step: 0.1,
type: 'number',
units: 'deg',
value: 0,
},
skewY: {
step: 0.1,
type: 'number',
units: 'deg',
value: 0,
},
R: {
range: [-255, 255],
type: 'number',
value: 7,
},
G: {
range: [-255, 255],
type: 'number',
value: 7,
},
B: {
range: [-255, 255],
type: 'number',
value: 7,
},
A: {
range: [-1, 1],
step: 0.05,
type: 'number',
value: 0,
},
},
setup: {
text: {
type: 'text',
value: 'TYPELAB',
},
font: {
type: 'select',
value: 'Bevan',
options: [...INITIAL_FONTS],
onFocus: async () => {
const localFonts = await getLocalFonts();
const availableFonts = [...INITIAL_FONTS, ...localFonts.map(font => font.fullName)].sort();
this.setState({
fields: {
...this.state.fields,
setup: {
...this.state.fields.setup,
font: {
...this.state.fields.setup.font,
options: availableFonts,
},
},
},
});
},
},
iterations: {
range: [1, Infinity],
type: 'number',
value: 38,
},
initialX: {
step: 10,
type: 'number',
value: 0,
},
initialY: {
step: 10,
type: 'number',
value: 0,
},
initialSize: {
range: [1, Infinity],
type: 'number',
value: 40,
},
initialR: {
range: [0, 255],
step: 5,
type: 'number',
value: 0,
},
initialG: {
range: [0, 255],
step: 5,
type: 'number',
value: 0,
},
initialB: {
range: [0, 255],
step: 5,
type: 'number',
value: 0,
},
initialA: {
range: [0, 1],
step: 0.1,
type: 'number',
value: 1,
},
},
},
};
},
formatValue(newVal, {range = [-Infinity, Infinity], type}) {
newVal += ''; // Cast to string.
if (type === 'select') return {value: newVal};
if (type === 'text') return {value: newVal.toUpperCase()};
const [min, max] = range;
const value = Math.min(Math.max(round(+newVal || 0, 3), min), max);
const isNumber = newVal.length && !isNaN(+newVal);
const isNegative = newVal[0] === '-';
const endsWithDecimal = newVal.slice(-1) === '.';
let displayValue = '';
if (isNumber) {
displayValue = value;
if (isNegative && value === 0) {
displayValue = '-' + displayValue;
}
} else if (isNegative) {
displayValue = '-';
}
if (endsWithDecimal) {
displayValue += '.';
}
return {displayValue, value};
},
onFieldChange(key, val) {
const {fields, page} = this.state;
const pageName = this.pageNames[page];
const currentFields = fields[pageName];
const editedField = currentFields[key];
this.setState({fields: {
...fields,
[pageName]: {
...currentFields,
[key]: {
...editedField,
...this.formatValue(val, editedField),
},
},
}});
},
pageNames: ['setup', 'functions'],
onPageChange(inc) {
const page = (this.state.page + inc) % this.pageNames.length;
this.setState({page});
},
onToggleClose() {
this.setState({closed: !this.state.closed});
},
render() {
const {closed, fields, page} = this.state;
const pageName = this.pageNames[page];
return <div style={styles.app}>
<Controls
closed={closed}
fields={fields[pageName]}
onFieldChange={this.onFieldChange}
onPageChange={this.onPageChange}
onToggleClose={this.onToggleClose}
page={pageName}
/>
<Canvas
fields={Object.assign({}, ...Object.values(fields))}
/>
</div>;
},
});
// Sadly, <input type="number"> is super jenky as a controlled input.
const Input = React.createClass({
propTypes: {
displayValue: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
]),
step: React.PropTypes.number,
onChange: React.PropTypes.func.isRequired,
onFocus: React.PropTypes.func,
range: React.PropTypes.arrayOf(
React.PropTypes.number.isRequired),
type: React.PropTypes.oneOf(['number', 'select', 'text']),
value: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
]).isRequired,
},
getDefaultProps() {
return {
step: 1,
};
},
bound(val) {
const {range, type} = this.props;
if (!range || type !== 'number' || isNaN(+val)) return val;
},
handleChange({target: {value}}) {
const {onChange} = this.props;
onChange(value);
},
handleKeyDown(e) {
const {step} = this.props;
switch (e.keyCode) {
// Up.
case 38:
this.setRepeater(step);
e.preventDefault();
break;
// Down.
case 40:
this.setRepeater(-step);
e.preventDefault();
break;
}
},
setRepeater(step) {
if (this.repeater) return;
const {onChange} = this.props;
// We access this.props.value here to get the most recent value.
this.repeater = setInterval(
() => onChange(this.props.value + step), 0);
},
clearRepeater() {
clearInterval(this.repeater);
delete this.repeater;
},
render() {
const {displayValue, step, type, value, options} = this.props;
const isSelect = type === 'select';
if (isSelect) {
return <div style={styles.inputContainer}>
<select
onChange={this.handleChange}
onFocus={this.props.onFocus}
style={styles.input}
value={value}
>
{options.map(option => <option
key={option}
value={option}
>{option}</option>)}
</select>
</div>;
}
const isNumber = type === 'number';
return <div style={styles.inputContainer}>
<input
onChange={this.handleChange}
onFocus={this.props.onFocus}
onKeyDown={isNumber && this.handleKeyDown}
onKeyUp={isNumber && this.clearRepeater}
style={styles.input}
type='text'
inputmode={isNumber ? type : 'latin'}
value={typeof displayValue !== 'undefined'
? displayValue
: value
}
/>
{isNumber && <button
onMouseDown={() => this.setRepeater(step)}
onMouseUp={this.clearRepeater}
style={{
...styles.controlButton,
...styles.incrementor,
top: 6,
}}
tabIndex='-1'
>▲</button>}
{isNumber && <button
onMouseDown={() => this.setRepeater(-step)}
onMouseUp={this.clearRepeater}
style={{
...styles.controlButton,
...styles.incrementor,
bottom: 6,
}}
tabIndex='-1'
>▼</button>}
</div>;
},
});
const Controls = React.createClass({
propTypes: {
closed: React.PropTypes.bool.isRequired,
fields: React.PropTypes.objectOf(React.PropTypes.shape({
displayValue: React.PropTypes.oneOfType([
React.PropTypes.number.isRequired,
React.PropTypes.string.isRequired,
]),
step: React.PropTypes.number,
range: React.PropTypes.arrayOf(React.PropTypes.number.isRequired),
type: React.PropTypes.string.isRequired,
value: React.PropTypes.oneOfType([
React.PropTypes.number.isRequired,
React.PropTypes.string.isRequired,
]).isRequired,
}).isRequired).isRequired,
onFieldChange: React.PropTypes.func.isRequired,
onToggleClose: React.PropTypes.func.isRequired,
page: React.PropTypes.string.isRequired,
},
handleSubmit(e) {
e.preventDefault();
},
render() {
const {
closed,
fields,
onFieldChange,
onPageChange,
onToggleClose,
page,
} = this.props;
const inputs = Object.entries(fields).map(
([key, val], i) => <label
key={i}
style={styles.label}
>
{key}
<Input
displayValue={val.displayValue}
step={val.step}
onChange={val => onFieldChange(key, val)}
onFocus={val.onFocus}
range={val.range}
type={val.type}
value={val.value}
options={val.options}
/>
</label>
);
const controlStyles = {...styles.controls};
const closeStyles = {...styles.controlButton, ...styles.close};
const containerStyles = {...styles.container};
if (closed) {
controlStyles.width = styleConstants.CONTROL_PADDING * 2;
closeStyles.transform = 'rotate(45deg)';
containerStyles.opacity = 0;
}
return <div style={controlStyles}>
<button
style={closeStyles}
onClick={onToggleClose}
>{'\u2716\uFE0E'}</button>
<div style={containerStyles}>
<div style={styles.title}>
<h1 style={styles.titleText}>{page}</h1>
<ul style={styles.pagination}>
<li style={styles.paginationItem}>
<button
onClick={() => onPageChange(-1)}
style={styles.controlButton}
>←</button>
</li>
<li style={styles.paginationItem}>
<button
onClick={() => onPageChange(1)}
style={styles.controlButton}
>→</button>
</li>
</ul>
</div>
<form
onSubmit={this.handleSubmit}
style={styles.form}
>{inputs}</form>
<a
href='https://twitter.com/rileyjshaw'
style={styles.link}
target='_blank'
>Created by @rileyjshaw.</a>
</div>
</div>;
},
});
const Canvas = React.createClass({
propTypes: {
fields: React.PropTypes.objectOf(React.PropTypes.shape({
value: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
]).isRequired,
})).isRequired,
},
render() {
const {
iterations: {value: iterations},
font: {value: font},
text: {value: text},
initialX: {value: initialX},
initialY: {value: initialY},
initialSize: {value: initialSize},
initialR: {value: initialR},
initialG: {value: initialG},
initialB: {value: initialB},
initialA: {value: initialA},
R: {value: R},
G: {value: G},
B: {value: B},
A: {value: A},
...transforms
} = this.props.fields;
const colors = [
[initialR, R],
[initialG, G],
[initialB, B],
[initialA, A]
];
const words = Array.from({length: iterations}, (_, i) => <li
key={i}
style={{
...styles.word,
color: `rgba(${colors.map(([a, b]) => Math.round(a + b * i))})`,
transform: Object.entries(transforms).map(([key, {value, units}]) => key +
`(${(FNS[key] || ((n, j) => n * j))(value, i + 1)}${units || 'px'})`
).join(' '),
zIndex: -i,
}}
>{text}</li>);
return <div style={{...styles.canvas, fontFamily: font}}>
<div style={{...styles.innerCanvas, fontSize: `${initialSize}px`}}>
<div style={styles.probe}>{text}</div>
<ul style={{
...styles.words,
transform: `translate(${initialX}px, ${initialY}px)`,
}}>{words}</ul>
</div>
</div>;
},
});
// Shared styles.
const styleConstants = {
CONTROL_WIDTH: 300,
CONTROL_PADDING: 24,
HEADER_FONT: 'Bevan, sans-serif',
};
const styleMixins = {
unlist: {
margin: 0,
padding: 0,
listStyle: 'none',
},
};
const styles = {
app: {
position: 'absolute',
top: 0,
left: 0,
height: '100%',
width: '100%',
display: 'flex',
},
controls: {
position: 'relative',
height: '100%',
width: styleConstants.CONTROL_WIDTH,
overflow: 'hidden',
font: '18px Inconsolata, sans-serif',
color: '#fff',
background: '#000',
transition: 'width 0.4s',
},
title: {
marginBottom: '2em',
borderBottom: '2px solid',
paddingBottom: '0.5em',
color: '#fff',
},
titleText: {
margin: 0,
fontFamily: styleConstants.HEADER_FONT,
},
controlButton: {
padding: 0,
border: 0,
fontSize: 24,
color: '#fff',
background: 'transparent',
cursor: 'pointer',
},
pagination: {
...styleMixins.unlist,
},
paginationItem: {
display: 'inline-block',
marginRight: 18,
},
close: {
position: 'absolute',
zIndex: 1,
top: styleConstants.CONTROL_PADDING / 2,
right: 14,
outline: 0,
transition: 'transform 0.2s 0.4s',
},
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
height: '100%',
width: styleConstants.CONTROL_WIDTH,
boxSizing: 'border-box',
padding: styleConstants.CONTROL_PADDING,
paddingBottom: 0,
transition: 'opacity 0.2s',
},
form: {
flexGrow: 1,
overflow: 'scroll',
},
label: {
display: 'flex',
marginBottom: '1em',
alignItems: 'center',
},
inputContainer: {
position: 'relative',
flexGrow: 1,
width: 0,
marginLeft: '1em',
},
input: {
width: '100%',
boxSizing: 'border-box',
border: 0,
padding: '0.5em 0.8em',
fontSize: '18px',
},
incrementor: {
position: 'absolute',
right: 8,
fontSize: 12,
color: '#000',
},
link: {
color: '#fff',
textDecoration: 'none',
display: 'block',
borderTop: '2px solid',
padding: '0.5em 0 0.8em',
},
canvas: {
position: 'relative',
zIndex: -1,
flexGrow: 1,
lineHeight: 1,
fontFamily: styleConstants.HEADER_FONT,
textAlign: 'center',
textTransform: 'uppercase',
},
innerCanvas: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
whiteSpace: 'nowrap',
},
probe: {
visibility: 'hidden',
},
words: {
...styleMixins.unlist,
position: 'absolute',
top: 0,
left: 0,
},
word: {
position: 'absolute',
// textShadow: '0 0 1px #fff',
},
};
const {body} = document;
const container = document.createElement('div');
ReactDOM.render(<App />, container);
body.style.overflow = 'hidden';
body.appendChild(container);
// Utils.
function round (val, decimals) {
return Number(Math.round(val + 'e' + decimals) + 'e-' + decimals);
}
Also see: Tab Triggers