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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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.

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.

HTML

              
                <h1 id="pg-title">Basic form with custom elements</h1>

<p class="sr-only">This form contains required fields.</p>
<p class="intro" aria-hidden="true">Required fields indicated with a <sup>*</sup></p>

<form id="simple-form" name="simple-form" action="form.html">
  <simple-input label="Name" required></simple-input>
  
  <simple-input
    label="Street Address"
    value="123 Main Street"
  ></simple-input>

  <h2>Submit button tests:</h2>

  <p>Fires <code>submit</code>, then browser runs validation:</p>
  <ul>
    <li>if it fails, submission stops</li>
    <li>if it passes, a <code>FormData</code> obj is created and <code>formdata</code> event fires</li>
  </ul>

  <div class="inline-buttons">
    <button class="button" id="submitDefault" type="submit">
      HTML built-in submit
    </button>

    <div class="button" role="button" tabindex="0" id="requestFn">
      <span><code>requestSubmit()</code></span>
      <span class="fineprint">Except in Safari &le;15</span>
    </div>
  </div>

  <p>Doesn't fire submit or validate, just fires <code>formdata</code>:</p>
  <div class="button" role="button" tabindex="0" id="submitFn">
    <span><code>submit()</code></span>
  </div>
</form>

<!-- for testing: -->
<div id="feedback"></div>
              
            
!

CSS

              
                * {
  box-sizing: border-box;
  font-family: sans-serif;
}
body {
  font-family: sans-serif;
  margin: 0 8vw;
  padding: 4vw 0;
}
h1, h2, h3 {
  margin: 1.5em 0 1em;
}
h1 {
  margin-top: 0;
}
code {
  font-family: 'Courier New', Courier, monospace;
  font-weight: bold;
}
p, li {
  font-size: 0.9rem;
  margin: 1.2rem 0 0.3rem;
}
ul {
  margin: .5rem 0 1rem;
}
li {
  margin: 0 0 .5rem;
}
simple-input,
simple-select {
  display: block;
  font-size: 0.9rem;
  margin: 1rem 0;
  max-width: 30rem;
}
.button {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 44px;
  background-color: #f6f6f6;
  color: #333;
  border: 1px solid #aaa;
  border-radius: 4px;
  padding: 0.3rem 1rem;
  margin: 0.3rem 0 1rem;
  font-size: 0.9rem;
}
.button:hover {
  background-color: #fff;
  border-color: #666;
  color: #000;
}
.inline-buttons {
  display: flex;
  gap: 1rem;
}
.fineprint {
  font-size: 0.8em;
  margin: 0.2em 0 0;
  opacity: 0.6;
}
.sr-only {
  position: absolute;
  top: 0;
  left: 0;
  width: 1px;
  height: 1px;
  overflow: hidden;
  opacity: 0;
}
.intro {
  font-style: ;
}
.intro sup {
  color: red;
  font-size: 1.2em;
  vertical-align: unset;
  margin-top: -1em;
  display: inline-block;
}
              
            
!

JS

              
                const simpleForm = document.getElementById('simple-form');
const submitBtn = document.getElementById('submitDefault');
const fauxSubmitBtn = document.getElementById('submitFn');
const requestBtn = document.getElementById('requestFn');
const feedback = document.getElementById('feedback');

// Bind submit & requestSubmit events for tests
fauxSubmitBtn.addEventListener('click', (e) => {
  simpleForm.submit();
});
requestBtn.addEventListener('click', (e) => {
  simpleForm.requestSubmit();
});

// Validate fields & create FormData object
simpleForm.addEventListener('submit', (e) => {
  alert('submit fired');

  // pause to allow validation
  e.preventDefault();

  let invalidFields = simpleForm.querySelectorAll('[invalid]');

  if (invalidFields.length > 0) {
    invalidFields.forEach((field) => {
      // apply styles
      field.isInvalid();
    });
    // focus the first invalid field
    invalidFields[0].focus();
  } else {
    // if no invalid fields, create FormData obj
    this.simpleData = new FormData(simpleForm);

    let fields = simpleForm.querySelectorAll('.field');
    fields.forEach((field) => {
      let name = field.getAttribute('label');
      let val = field.getAttribute('value');
      this.simpleData.set(name, val);
    });

    // replace with submission logic:
    let feedbackArr = [];
    for (let [name, value] of this.simpleData) {
      feedbackArr.push(`${name}: ${value}`);
    }
    feedback.innerHTML = `<h3>Form values:</h3>` + feedbackArr.join(', ');
  }
});

simpleForm.addEventListener('formdata', (e) => {
  alert('formdata fired');
  e.preventDefault();
});

class SimpleInput extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({
      mode: 'open',
      delegatesFocus: true,
    });

    const label = document.createElement('label');
    const labelText = document.createElement('span');
    const errorMssg = document.createElement('p');
    labelText.classList.add('label-text');
    labelText.textContent = this.getAttribute('label');
    errorMssg.setAttribute('id', 'input-error');
    errorMssg.classList.add('error-message');

    const input = document.createElement('input');
    input.setAttribute('aria-describedby', 'input-error');

    // set default value, if any
    if (this.hasAttribute('value')) {
      let val = this.getAttribute('value');
      if (val) input.value = val;
    }

    // check for required attr
    if (this.hasAttribute('required')) {
      // set corresponding input property
      input.required = true;
      // by default, the field is invalid until filled in
      this.setAttribute('invalid', true);
      // add indicator, styles
      labelText.innerHTML = labelText.innerHTML +=
        '<sup aria-hidden="true">*</sup>';
      labelText.classList.add('required');
    }

    this.isInvalid = () => {
      this.setAttribute('invalid', true);
      errorMssg.textContent = 'Please enter a value.';
      input.classList.add('invalid');
    };

    this.isValid = () => {
      this.removeAttribute('invalid');
      errorMssg.textContent = '';
      input.classList.remove('invalid');
    };

    input.addEventListener('change', (e) => {
      // sync value with attr
      this.setAttribute('value', input.value);

      // dispatch change event that bubbles from the input
      let changeEv = new Event('change', { bubbles: true });
      this.dispatchEvent(changeEv);
    });

    input.addEventListener('blur', (e) => {
      // run client-side validation
      if (input.validity.valueMissing) {
        this.isInvalid();
      } else {
        this.isValid();
      }
    });

    const style = document.createElement('style');
    style.textContent = `
      label {
        display: flex;
        flex-flow: row nowrap;
      }
      .label-text {
        flex: 0 0 8rem;
      }
      .label-text sup {
        color: red;
        font-size: 1.2em;
        vertical-align: unset;
        margin-top: -1em;
        display: inline-block;
      }
      .error-message {
        font-size: .9em;
        margin: .3rem 0 0 8rem;
        color: #b50000;
      }
      input {
        width: 100%;
        border: 1px solid #666;
        padding: .3rem;
        border-radius: 4px;
      }
      input.invalid {
        border-color: #b50000;
        outline-color: red;
      }
    `;

    this.classList.add('field');

    label.appendChild(labelText);
    label.appendChild(input);
    shadow.appendChild(style);
    shadow.appendChild(label);
    shadow.appendChild(errorMssg);
  }
}

customElements.define('simple-input', SimpleInput);

              
            
!
999px

Console