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 class="container-fluid">
<div class="row align-items-center justify-content-center fullheight">
<div class="col-10 col-sm-8 col-md-6 col-lg-5">
<div class="card shadow-lg card--bg-gray card--customized">
<div class="card-body">
<h1 class="card-title">Form with Floated Labels in Vanilla Javascript</h1>
<form id="myform">
<div class="mb-2 control-wrapper">
<div class="label-container">
<label for="exampleInputText" class="form-label">Your name (CAPITAL LETTERS only)</label>
</div>
<input type="text" class="form-control" id="exampleInputText" required pattern="[A-Z]*">
<div class="display-msg"></div>
</div>
<div class="mb-2 control-wrapper">
<div class="label-container">
<label for="exampleInputEmail" class="form-label">Email address</label>
</div>
<input type="email" class="form-control" id="exampleInputEmail">
<div class="display-msg"></div>
</div>
<div class="mb-2 control-wrapper">
<div class="label-container">
<label for="exampleInputPassword" class="form-label">Password</label>
</div>
<input type="password" class="form-control" id="exampleInputPassword" minlength="3" maxlength="10">
<div class="display-msg"></div>
</div>
<div class="mb-2 control-wrapper">
<div class="label-container">
<label for="exampleTextarea" class="form-label">Your message</label>
</div>
<textarea class="form-control" id="exampleTextarea" rows="3" required></textarea>
<div class="display-msg"></div>
</div>
<div class="mb-4 form-check control-wrapper">
<div class="label-container">
<label class="form-check-label" for="exampleCheck">I have read your private policy and hereby confirm it.</label>
<input type="checkbox" class="form-check-input" id="exampleCheck" required>
<div class="display-msg"></div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous" />
</body>
// Sass Variables
$body-background-color-from: #544a7d;
$body-background-color-to: #ffd452;
$card-background-color-from: #d3cce3;
$card-background-color-to: #e9e4f0;
$durationNumber: 180;
$duration: ($durationNumber / 1000) * 1s;
$label-font-size: 1rem;
$label-font-size-shrinked: 0.8rem;
$label-font-color: #777;
$label-font-color-shrinked: #111;
$label-margin: 0.2rem;
$label-padding-left: 0.75rem;
$msg-color: #c03030;
$msg-slide-x-gap: 40px;
$form-control-font-size: 1rem; // Default Bootstrap 5
$form-control-padding-y: 0.375rem; // Default Bootstrap 5
// CSS Variables
:root {
--field-adjust-y: calc(
#{$label-font-size-shrinked} + #{$label-margin} +
calc((#{$form-control-font-size} + #{$form-control-padding-y}) / 2)
);
--durationNumber: #{$durationNumber};
}
*,
*::before,
*::after {
box-sizing: border-box;
}
// Font
@import url('https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;800&display=swap');
body {
font-family: 'Fira Sans', 'Arial', 'Helvetica', sans-serif;
background: linear-gradient(90deg, $body-background-color-from 0%, $body-background-color-to 100%);
}
h1 {
font-size: 1.8rem;
font-weight: bold;
}
.fullheight {
min-height: 100vh;
}
.card--bg-gray {
background: linear-gradient(0deg, $card-background-color-from 0%, $card-background-color-to 100%);
}
.card--customized {
border-radius: 0.5rem;
}
.control-wrapper {
display: grid;
grid-template-rows: ($label-font-size + $label-margin) auto ($label-font-size + $label-margin);
&.form-check {
grid-template-rows: auto;
}
& .label-container {
position: relative;
& > label {
position: absolute;
top: var(--field-adjust-y);
left: $label-padding-left;
font-size: $label-font-size;
font-weight: 800;
color: $label-font-color;
transition: top $duration ease-in-out, left $duration ease-in-out, font-size $duration ease-in-out,
color $duration ease-in-out;
}
}
&.form-check .label-container {
display: grid;
grid-template-rows: auto ($label-font-size + $label-margin);
& > label {
grid-area: 1 / 1 / 2 / 2;
position: static;
}
& > input {
grid-area: 1 / 1 / 2 / 2;
position: static;
}
& > .display-msg {
grid-area: 2 / 1 / 3 / 2;
margin-left: -1.5rem;
}
&::after {
display: none;
}
}
&.field--focused,
&.field--notempty {
& .label-container {
& > label {
position: absolute;
top: 0;
left: 0;
font-size: $label-font-size-shrinked;
color: $label-font-color-shrinked;
}
}
}
& .label-container,
& .display-msg {
&::after {
content: '.';
opacity: 0;
}
}
& .label-container {
margin-bottom: $label-margin;
}
& > .display-msg,
.label-container > .display-msg {
margin-top: $label-margin;
font-size: $label-font-size-shrinked;
color: $msg-color;
opacity: 0;
transform: translate($msg-slide-x-gap, 0);
transition: opacity $duration ease-in-out, transform $duration ease-in-out;
}
&.field--invalid > .display-msg,
.label-container.field--invalid > .display-msg {
transform: translate($msg-slide-x-gap, 0);
opacity: 1;
transform: translate(0, 0);
&.slide-out {
opacity: 0;
transform: translate(-$msg-slide-x-gap, 0);
}
}
}
class FormApp{
constructor(formId){
this.form = document.getElementById(formId);
if (this.form){
let fields = this.form.querySelectorAll(`input:not([disabled]):not([type="submit"]), textarea:not([disabled])`);
this.fields = Array.prototype.slice.call(fields, 0).filter(x => x !== null);
this.fields.forEach(field => {
FormApp.checkIfFieldIsFilled(field);
})
}
}
// Customized Error Messages. Keys compatible to ValidityState of Validation API
static errorMsg = {
valueMissing: "Please enter the mandatory input fields.",
typeMismatch: "Please enter a valid Email address.",
patternMismatch: "Your input doesn´t match the pattern.",
tooLong: "Your input is too long.",
tooShort: "Your input is too short.",
rangeUnderflow: "Your input is below the allowed range.",
rangeOverflow: "Your input is beyond the allowed range.",
stepMismatch: "Your input doesn´t fit the rules.",
badInput: "Browser cannot handle your input.",
customError: "A custom error occured."
}
// Static methods
static getValueFromInput(field, trim = true) {
let input = field.value;
if (field.type === `checkbox`) {
input = field.checked;
} else {
input = trim ? input.trim() : input;
}
return input;
}
static checkIfFieldIsFilled = (field) => {
if (field.type !== `checkbox`) {
if (FormApp.getValueFromInput(field).length > 0) {
field.parentElement.classList.add(`field--notempty`);
return true;
} else {
field.parentElement.classList.remove(`field--notempty`);
return false;
}
} else {
return field.checked;
}
};
init = () => {
this.form.setAttribute('novalidate', true);
this.registerEventListeners();
}
registerEventListeners = () => {
const currentlySupportedTypes = [`text`, `email`, `password`, `number`, `tel`, `time`, `url`, `textarea`, `checkbox`];
const eventListeners = [
{
name: 'focus',
handler: this.handleFocus,
},
{
name: 'input',
handler: this.handleInput,
},
{
name: 'blur',
handler: this.handleBlur,
},
]
this.fields.map(field => {
const type = field.type;
if (currentlySupportedTypes.includes(type)){
eventListeners.map(el => {
field.addEventListener(el.name, el.handler);
})
}
})
if (this.form){
this.form.addEventListener('submit', this.handleSubmit)
}
}
handleFocus = (event) => {
let evt = event || window.event;
let field = evt.target;
if (field !== undefined){
field.parentElement.classList.add(`field--focused`);
}
};
handleInput = (event) => {
let evt = event || window.event;
let field = evt.target;
if (field !== undefined){
FormApp.checkIfFieldIsFilled(field);
this.validateField(field);
}
};
handleBlur = (event) => {
let evt = event || window.event;
let field = evt.target;
if (field !== undefined){
field.parentElement.classList.remove(`field--focused`);
FormApp.checkIfFieldIsFilled(field);
this.validateField(field);
}
};
handleSubmit = (event) => {
let evt = event || window.event;
evt.preventDefault();
let arr = this.fields.map(field => {
return this.validateField(field);
}).filter(field => !field);
if (arr.length === 0){
// No Errors client-side: Here you would process the data
let str = this.fields.map(field => {
let key = field.labels[0].textContent;
let value = FormApp.getValueFromInput(field)
return `${key}: ${value}`;
}).join(`\n`);
window.alert("SUBMIT SUCCESSFUL\n\n" + str);
}
}
validateField = (field) => {
const validState = field.validity;
let err_content = '';
if (validState){
let error_arr = []
for(var key in validState){
if (validState[key]){
error_arr.push(key);
}
}
error_arr = error_arr.filter(item => item !=='valid');
const error = error_arr.length > 0 ? error_arr[0]:'';
let msg = field.parentElement.querySelector(`.display-msg`);
let msgClist = msg.classList;
err_content = FormApp.errorMsg.hasOwnProperty(error) ? FormApp.errorMsg[error]:'';
let durationNumber = parseInt(window.getComputedStyle(document.documentElement).getPropertyValue('--durationNumber'));
let cList = field.parentElement.classList;
let setFieldInvalid = () => {
msg.textContent = err_content;
cList.add(`field--invalid`);
}
if ( error_arr.length > 0 ){
this.form.classList.add(`was-validated`);
if (!msgClist.contains(`slide-out`)){
setFieldInvalid();
} else {
setTimeout(setFieldInvalid, durationNumber);
}
} else {
msgClist.add(`slide-out`);
setTimeout(function(){
cList.remove(`field--invalid`);
msgClist.remove(`slide-out`);
}, durationNumber)
}
}
return err_content.length > 0 ? false : true;
}
}
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(() => {
const init = () => {
const myForm = new FormApp("myform");
myForm.init();
}
init();
});
Also see: Tab Triggers