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.
<body>
<div id="root"></div>
</body>
@import url('https://fonts.googleapis.com/css2?family=Dongle&family=Roboto:wght@400;900&display=swap');
:root {
--black: #000000;
--white: #ffffff;
--background-color: #303030;
--text-color: #ffffff;
}
* {
padding: 0;
margin: 0;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
input:-webkit-autofill,
input:-webkit-autofill:focus {
-webkit-box-shadow: 0 0 0 50px var(--background-color) inset; /* Change the color to your own background color */
-webkit-text-fill-color: var(--text-color);
}
const { createTheme, ThemeProvider, CssBaseline, Container, Grid, Paper, Box, TextField, Typography, Button, MenuItem } = MaterialUI;
type InitType = {
[key: string]: any
}
type FormProps = {
title?:string
}
type FormValidationItemType = {
regex: RegExp,
errorMsg: string
}
type FormValidationType = {
[key: string]: {
value: string,
label: string,
required?: boolean,
valid: boolean,
validation: Array<FormValidationItemType>,
select?: Array<string>
}
}
const NO_ERROR = ' '; // empty char in order to display helper text field permanently
const FIELD_REQUIRED = {regex: /\S/g, errorMsg: 'Mandatory Field'};
const TITLE = 'Please provide your contact details:';
const ALERT = 'Your input Data:\n\n';
const theme = createTheme({
palette: {
mode: 'dark',
primary: {
main: '#fb8c00',
},
secondary: {
main: '#b2ff59',
},
background: {
default: '#303030',
paper: '#303030'
}
},
typography: {
fontFamily: ['Roboto', 'sans-serif'].join(','),
fontSize: 16,
h1: {
fontSize: '4.4rem',
},
h2: {
fontSize: '3.6rem',
},
button: {
fontSize: '1.2rem',
}
},
});
const initValue: FormValidationType = {
title: {
value: '',
label: 'Title',
valid: true,
required: false,
validation: [],
select: ['Ms.', 'Mrs.', 'Mr.'],
},
firstName: {
value: '',
label: 'First Name',
valid: true,
required: true,
validation: [
{regex: /[0-9a-zA-Z]{3,}/g,
errorMsg: 'Less than 3 or invalid characters.'},
],
},
lastName: {
value: '',
label: 'Last Name',
valid: true,
required: false,
validation: [
{regex: /[0-9a-zA-Z]{3,}/g,
errorMsg: 'Less than 3 or invalid characters.'},
],
},
age: {
value: '',
label: 'Your age',
valid: true,
required: true,
validation: [
{regex: /^[0-9]{1,3}$/g,
errorMsg: 'You need to input a valid number.'},
],
},
email: {
value: '',
label: 'Email',
valid: true,
required: false,
validation: [
{regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/g,
errorMsg: 'Invalid email address.'},
],
},
}
const useFormValidation = (props: FormValidationType) => {
const {initValue, initValid, initHelperText} = getInitValues();
const [value, setValue] = React.useState(initValue);
const [isValid, setIsValid] = React.useState(initValid);
const [helperText, setHelperText] = React.useState(initHelperText);
function getInitValues(){
let initValue: InitType = {};
let initValid: InitType = {};
let initHelperText: InitType = {};
for (const [key, value] of Object.entries(props)) {
initValue[key] = value.value;
initValid[key] = value.valid;
initHelperText[key] = NO_ERROR;
}
return {initValue, initValid, initHelperText};
}
let obj: InitType = {};
for (const [key, val] of Object.entries(props)) {
obj[key] = {
value: value[key],
isValid: isValid[key],
required: val.required,
bind: {
value: value![key],
onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
setValue(prev => {
return {...prev, [key]: event.target.value};
});
const required = event.target.required;
let validationArr = required ? [FIELD_REQUIRED]: [];
validationArr = validationArr.concat(val.validation);
let errArr = validationArr.map(v => {
return event.target.value.search(v.regex);
});
let validationState = errArr.filter(i => i < 0).length === 0 ? true : false;
let index = errArr.findIndex(e => e === -1 );
let errorMsg = validationState ? NO_ERROR : validationArr[index].errorMsg;
setHelperText(prev => {
return {...prev, [key]: errorMsg};
});
setIsValid(prev => {
return {...prev, [key]: validationState};
});
},
helperText: isValid[key] ? NO_ERROR : helperText![key],
error: !isValid[key],
},
}
}
obj.resetValue = () => {
const {initValue, initValid, initHelperText} = getInitValues();
setValue(initValue);
setIsValid(initValid);
setHelperText(initHelperText);
}
return obj;
}
const Form = (props: FormProps) => {
const {title} = props;
const obj = useFormValidation(initValue);
let valid = Object.keys(initValue).map(item=>{
let isValid = obj[item].isValid;
let isNotRequired = obj[item].required ? false : true;
let isRequiredAndNotEmpty = isNotRequired ? true: obj[item].value.length > 0;
return isValid && isRequiredAndNotEmpty ;
}).filter(x=>x).length === Object.keys(initValue).length;
function sumbmit(){
let str = ALERT;
str += Object.keys(obj).map(item=>obj[item].value).join('\n');
alert(str);
}
function reset(){
obj.resetValue();
}
return <Box sx={{
margin: 0,
padding: 2,
'& .MuiInput-root': {
transition: theme=> theme.transitions.create(['background-color'], {
duration: theme.transitions.duration.standard,
easing: theme.transitions.easing.easeInOut,
}),
'&.Mui-focused' : {
backgroundColor: 'background.default',
}
},
}}>
{title && (<Box><Typography variant="h3" sx={{fontWeight: 800, fontSize: '1.5rem', lineHeight: 1.1, mb: 2}}>{title}</Typography></Box>)}
<Box>
{
Object.keys(initValue).map((item, index)=>{
const itemObj = initValue[item];
return (
<TextField variant="standard" size="medium" key={index} fullWidth id={item} {...obj[item]?.bind} label={itemObj.label} autoComplete="off" select={itemObj.select && itemObj.select.length > 0}>
{
itemObj.select && (
itemObj.select.map((sel, selIndex)=> {
return (<MenuItem key={selIndex} value={ sel }>{ sel }</MenuItem>)
})
)
}
</TextField>)
})
}
</Box>
<Box display="flex" justifyContent="space-around" sx={{my: 2}}>
<Button variant="contained" onClick={reset}>Reset</Button>
<Button variant="contained" disabled={!valid} onClick={sumbmit}>Send</Button>
</Box>
</Box>;
};
function App() {
return (
<ThemeProvider theme={theme}>
<CssBaseline>
<Container maxWidth="md" >
<Grid container spacing={1} justifyContent="center" alignItems="center" sx={{minHeight: '100vh'}}>
<Grid item></Grid>
<Grid item xs={10} sm={8} md={6}>
<Paper elevation={12} >
<Form title={ TITLE } />
</Paper>
</Grid>
<Grid item></Grid>
</Grid >
</Container>
</CssBaseline>
</ThemeProvider>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Also see: Tab Triggers